Privacy Policy
© 2026 linux101.dev

history Command Cheatsheet

The history shell builtin shows the list of previous commands. It is very useful for recall, reuse, and command-line productivity in Bash and compatible shells.

Where History is Stored

Bash saves command history in ~/.bash_history by default when a shell session ends. The in-memory history for the current session is also available in the HISTFILE and HISTSIZE settings.

  • echo $HISTFILE (usually ~/.bash_history)
  • echo $HISTSIZE (number of commands saved in memory)
  • echo $HISTFILESIZE (max number of lines in history file)

To immediately append the current session history to the file: history -a.

Basic History Commands

history
Display the current session command history with command numbers.

history | tail -n 20
Show only the last 20 commands from history for quick review.

history -c
Clear the current session history (in-memory only).

history -w
Write the current session history to $HISTFILE immediately.

Reverse Search Shortcut (Ctrl+R)

Press Ctrl+R in an interactive shell to start incremental reverse-i-search. Type part of a command and Bash will display matching history entries.

Successfully matched command can be run by pressing Enter, edited with Right Arrow, or canceled with Ctrl+C.

History Expansion with !

Bash supports quick re-execution and expansion using ! notation. Examples:

  • !! - repeat last command
  • !n - run command number n from history
  • !-2 - run the command from two steps ago
  • !git - repeat the last command starting with git
  • !$ - last argument of previous command (e.g. cd !$)
  • ^old^new^ - quick substitution (re-run last command with replacement)

To preview the expansion without running, add :p, e.g. !ls:p.

History Configuration Tips

  • HISTCONTROL=ignoredups:erasedups avoids duplicate entries.
  • shopt -s histappend appends history instead of overwriting.
  • export PROMPT_COMMAND='history -a' saves each command immediately.

In multiple simultaneous shells, each session has its own in-memory history and only writes to $HISTFILE on exit (or with history -a). Use history -a + history -n to share updates safely between active windows.