3. Command history
-
The command
historycan be used to display the history of the typed commands:historyhistory | lesshistory | tailhistory | tail -n 20history | grep man -
The history is kept of in the file
~/.bash_history:echo $HISTFILEls $HISTFILEtail $HISTFILENotice that the latest commands are not there. Bash maintains the list of commands internally in memory while it's running, and writes it to the history file on exit. Let's tell Bash to append the command list to the history file now:
history -atail $HISTFILE -
We can re-run a previous command like this:
!67Rerun the command which has the given number.
!lsRerun the last command that starts with
ls.!?passwdRerun the last command that contains
passwd.history | grep passwd -
We can recall the previous commands also by pressing the up-arrow multiple times.
-
However the most useful way to rerun previous commands is searching interactively, with keyboard shortcuts.
For example typing "Ctrl-r" will start a reverse incremental search. It is "reverse" because it searches backwards in the history list, starting from the last command. While we start typing the search text it will display the last command that matches it. If we are happy with the search result we can just press enter to rerun it, or we can use the left and right arrows to edit it first and then press [Enter] to run it. Otherwise we can keep pressing "Ctrl-r" to get the next matching command, and so on.
Let's try it:
-
Press "Ctrl-r".
-
Type "pass".
-
Press "Ctrl-r" again.
-
Press "Ctrl-r" again.
-
Press "Enter".
-