Linux Bash History

Posted on 7:12 PM by Bharathvn

The Bourne Again Shell (bash) is the shell used by default by most modern Linux systems and quite a few other operating systems such as Mac OS X. Built into bash, as with other shells, is a history feature that lets you review, change, and reuse commands that you have run in the past. This can prove very helpful as many Linux commands are long and complicated.

When bash starts, it reads the ~/.bash_history file and loads it into memory. This
file is set by the value of $HISTFILE.

NOTE See the section “Using Environment Variables” later in this chapter for
more on how to work with shell environment variables such as $HISTFILE. During a bash session, commands are added to history in memory. 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:

$ echo $HISTFILE $HISTSIZE $HISTFILESIZE

/home/fcaen/.bash_history 500 500

To list the entire history, type history. To list a previous number of history commands, follow history with a number. This lists the previous five commands in your history:

$ history 5
975 mkdir extras
976 mv *doc extras/
977 ls -CF
978 vi house.txt
979 history

To move among the commands in your history, use the up arrow and down arrow. 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. Here are some other ways to recall and run commands from your bash history:

$ !! Run the previous command
$ !997 Run command number 997 from history
ls -CF
$ !997 *doc Append *doc to command 997 from history
ls -CF *doc
$ !?CF? Run previous command line containing the CF string
ls -CF *doc
$ !ls Run the previous ls command
ls -CF *doc
$ !ls:s/CF/l Run previous ls command, replacing CF with l
ls -l *doc

Another way to edit the command history is using the fc command. With fc, you open
the chosen command from history using the vi editor. The edited command runs when you
exit the editor. Change to a different editor by setting the FCEDIT variable (for example, FCEDIT=gedit) or on the fc command line. For example:

$ fc 978 Edit command number 978, then run it
$ fc Edit the previous command, then run it
$ fc -e /usr/bin/nano 989 Use nano to edit command 989

Use Ctrl+r to search for a string in history. For example, typing Ctrl+r followed by the string ss resulted in the following:
#
(reverse-i-search)`ss’: sudo /usr/bin/less /var/log/messages
Press Ctrl+r repeatedly to search backwards through your history list for other occurrences of the ss string.