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
historyhistory | tail -n 20history -chistory -w$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 numbernfromhistory!-2- run the command from two steps ago!git- repeat the last command starting withgit!$- 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:erasedupsavoids duplicate entries.shopt -s histappendappends 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.