Thursday, May 3, 2007

Using the Bash History

The command history is stored in ~/.bash_history. The history typically contains the last 500 commands typed at the shell prompt.

You can view the history by using the history command.

history | less

Then you can search for a command.

e.g. what was the name of that directory I created yesterday? Oh, yeah, I can search history for the mkdir command by using the slash.

/mkdir

You could also use grep, but with less, you can see the surrounding commands, as you often want to see the sequence of what was done.

History Shortcuts

  • !! - Executes the last command

  • !902 - Executes command number 902 (from the history list)

  • !service - Executes the command whose string matches the most recent history entry

  • Up / Down - The most common shortcut is to simply use the up and down arrows to scroll through the bash history.


Example
If you recently restarted the network service, and then wanted to restart it again, you might do something like this;

service network restart
ping somehost.example.com

You see that the network is unreachable.

Then you remember that you misconfigured something, such as gateway so you modify it:

vi /etc/sysconfig/network-scripts/ifcfg-eth0

Now, rather than typing the entire command again "service network restart", you can simply type:

!serv

A similar shortcut can be used when you forget to type sudo.
e.g.

$ mkdir /root/test
mkdir: cannot create directory `/root/test': Permission denied
$ sudo !!
sudo mkdir /root/test
$

Or, to change the previous command, while keeping the parameter, use "!$"

e.g., change cat to vi, but keep the rest of the line
$ cat /etc/resolv.conf
search example.com
nameserver 192.xxx.xxx.xxx
$ vi !$
vi /etc/resolv.conf


see also http://systemnotesorg.blogspot.com/2007/03/unix-linux-command-tips.html

No comments: