Command line editing and bash

It's known that use of commands as opposed to use of some GUI and mouse saves a lot of time. On a command prompt, you can use shortcuts like tab for command completion arrow keys to issue the commands in the History. Many users know Ctrl+a and Ctrl+e to go to the start and end of the line. Some know Alt+f and Alt+b are used for moving forward or backward one word at a time. But it stops there for the most. Of course, the above shortcuts can be customized by creating your own ~/.inputrc file.

On this page, we cover some less frequently (and probably new to you) shortcuts which you can use in Bash for quick command line editing. All these key-bindings and commands are given in the READLINE section of bash man-page but for a newbie it is not easy to follow.

Try this out
!start_of_command
e.g.   !ftp

This issues the last ftp command. You do not have to type that big host-name ! You can even try !ft. If there is no other command than 'ftp' that starts with 'ft', the shell will issue the last ftp-command. If you did not issue any command that starts with 'start_of_command', you get a message 'event not found'. An exclamation mark (!) is related to events in bash. !! means the last command line where as !# refers to the current command-line.

If you want to see which ftp command you executed last,

!ftp:p gives you the info.

Now that you have been reading this so far, it's worth trying the following at the command-prompt

echo !ftp:1

or echo !ftp:0

You can even give range for words like

echo !start_of_command:0-2

This will echo the first three words of the command.

history command gives the output in the following format

some_number command

This 'some_number' is the event so if you just issue,

!465
the shell will execute the command assosiated with the even number 465.

You can even search the command line. Press 'Ctrl-r' on the command prompt. You'll see
(reverse-i-search)`':

Now start typing the search-phrase. Your command appears on the prompt. Just pressing 'Enter' will issue the command. This is handy when you want to search through the history of commands and issue after some editing. Saves a lot of time.

Back to Linux Tips