Skip to main content

3. Command history

  1. 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
  2. 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
  3. 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
  4. We can recall the previous commands also by pressing the up-arrow multiple times.

  5. 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:

    1. Press "Ctrl-r".

    2. Type "pass".

    3. Press "Ctrl-r" again.

    4. Press "Ctrl-r" again.

    5. Press "Enter".

Loading asciinema cast...