Sunday, July 5, 2009

Learning (from) bash history

The Bourne Again Shell (bash) is the default shell in almost all Linux distributions. The bash shell has a history feature which can make life easier for any serious Linux user.
Open a shell and try the following .

/home/fermi/.bash_history 500 500

The HISTFILE environment variable points to the name of the file where bash history is stored. When bash exits, history in memory is written back to the .bash_history file. The number of commands held in history during a bash session is set by $HISTSIZE, while the number of commands actually stored in the history file is set by $HISTFILESIZE.

You can use history command to list the entire command line history.
You can list the last n entries in the history as below. (n=5)

$history 5
424 man fc
426 history
427 history 10
428 history 5

You can use up arrow and down arrow keys to move around the history buffer.Once a command is displayed, you can use the keyboard to edit the current command like any other command: left arrow, right arrow, Delete, Backspace, and so on.

There are some other tricks you can use .

~$ !! run the previous command
~$ !427 run command numbered 427 from history
~$ !423 *.jpg append *.jpg to command 423
~$ !ls run previous command starting with ls

You can search command history for a specific string by pressing Crtl together with r

$ <Ctrl+r> ( You will not see this)

You can type in the string to be searched after the colon and press enter.
You can press Ctrl+r repeatedly to search backwards through your history list for a specific occurrence of the string.

There is another way of editing the history using fc command. Try this

$fc -e vim 427

This will open command 427 in vim and you can edit it and save it back to history. RTFM fc for details.

No comments: