3. Command history
-
The command
history
can be used to display the history of the typed commands:history
history | less
history | tail
history | tail -n 20
history | grep man
-
The history is kept of in the file
~/.bash_history
:echo $HISTFILE
ls $HISTFILE
tail $HISTFILE
Notice 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 -a
tail $HISTFILE
-
We can re-run a previous command like this:
!67
Rerun the command which has the given number.
!ls
Rerun the last command that starts with
ls
.!?passwd
Rerun 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".
-