Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comment out a command line in bash using Readline

The Situation

I am writing a very long command in bash and eventually realise that I forgot to satisfy a prerequisite for that command. I want to store this command somewhere, perform all the requirements, restore the command back and execute it.

Note: I want the command to stay on the screen

Here is an example:

$ a very long command --path some_path and more arguments

So suppose this command requires that the some_path is an existing directory. However, while writing the command, I realise that I have not created that directory, so before executing the command I have to mkdir some_path.

The Requirement

What I would like to be able to do is the following:

$ a very long command --path some_path and more arguments [keystroke -> comment]
$ mkdir some_path
$ [up] [up] [keystroke -> uncomment]

or...

$ a very long command --path some_path and more arguments [keystroke -> comment]
$ mkdir some_path
$ [keystroke -> bring back, uncomment]

My Solution

To solve this problem I used the Readline bind tool and mapped Control-P character to a custom script in the following way:

function postpone {
   if [[ ${#READLINE_LINE} -gt 0 ]]
   then
      if [[ "${READLINE_LINE::1}" == "#" ]]
      then
         READLINE_LINE="${READLINE_LINE:1}"
      else
         READLINE_LINE="#$READLINE_LINE"
      fi
   else
      HIST_SIZE=`history | wc -l | tr -s ' ' | cut -d \  -f 2`
      for i in $(seq 1 $HIST_SIZE)
      do
         LINE=`history | sort -r | head -n $i | tail -n 1 | tr -s ' ' | cut -d \  -f 3-`
         if [[ "${LINE::1}" == "#" ]]
         then
            READLINE_LINE="${LINE:1}"
            break
         fi
      done
   fi
}

bind -x '"\C-b": postpone'
bind '"\C-p":"\C-b\n"'

And finally...The Question

Can you suggest a better solution where I can go with a single mapping? The main focus is to eliminate the second mapping.

Notes

I learnt about insert-comment bind function, but it will not work for me, as it only works on one direction. I also want to uncomment the line using the same shortcut.

like image 339
bagrat Avatar asked Oct 23 '25 16:10

bagrat


1 Answers

An alternative:

  1. At the end of your long line press Ctrl+u.
  2. mkdir some_path
  3. Press Ctrl+y and continue your work.
like image 139
Cyrus Avatar answered Oct 25 '25 05:10

Cyrus