Repeating and editing previous commands

The command history lists previous commands with numbers. You can run any previous command by typing ! followed by the command number. For example, if the output of thehistory command is as follows:

181     ls
182     ls
183     cat /etc/shells
184     cat /etc/hosts
185     w

Then you can run the command 183 again as follows:

[alice@localhost]: !183
cat /etc/shells
/bin/bash
/bin/sh
/bin/ash
/bin/bsh
/bin/bash2
/bin/tcsh
/bin/csh
/bin/ksh
/bin/zsh
[alice@localhost]:

Alternately, we can use ! followed by a prefix of the command and the shell searches for and executes the last command that started with the given prefix. In the above example, saying!cat, will result in the command cat /etc/hosts to be executed.

Typing two bang characters is a short-cut for repeating the last command.

[alice@localhost]: date
Mon Oct 25 14:29:19 MDT 2012
[alice@localhost]:!!
date
Mon Oct 25 14:29:23 MDT 2012
[alice@localhost]:

You can use the arrow keys ($\uparrow$ and $\downarrow$) to go up and down the list of commands that you typed into the shell until you reach the desired command. You can use backspace and arrow keys ($\leftarrow$ and $\rightarrow$) to edit the command. Press the ENTER key to execute the command.

You can also set the editor mode for the bash shell to be Vi (or Emacs) by placing the following command in your .bash_profile file.
set -o vi
Vi (actually Vim, which is a superset of Vi) and Emacs are two powerful text editors. We will be learning Vim in the next chapter.

If you wish to use the more powerful editing commands from vi, type in the ESC key. Now you can use the vi search command /string to search for a previous command containing that string. Once you get to the desired command you can edit it further using the standardvi editing commands. After you are done editing just type ENTER to execute the command.

Another common technique is to grep through the history to find the command you had typed earlier.

[alice@localhost C-examples]: history | grep javac
 8202  javac
 8206  javac WebStats.java
 8211  javac -O WebStats.java
10082  history | grep javac
[alice@localhost C-examples]:

Here the vertical bar symbol | is the pipe symbol that connects the two commands history and grep together. This is an example of object composition!

On a the GUI desktop you can use the mouse to cut and paste previous commands. See Chapter 7 for more details.