history Command Cheat Sheet
The history command lists the commands previously executed by the user. It is a shell builtin (Bash, Zsh) essential for auditing and improving CLI productivity.
Basic Usage
View History
history
View Last N Commands
history 10
Searching and Expansion
Reverse Search (Ctrl+R)
Press Ctrl+R and start typing. The shell will find the most recent matching command.
- Press Ctrl+R again to cycle backwards.
- Press Enter to run found command.
- Press Right Arrow to edit.
Run by Number (!)
!450
Run Last Command (!!)
!!
sudo:
sudo !!
Run Last Command Starting String (!string)
!vim
vim).
Search and Replace (Quick Substitution)
^old^new
old with new.
Example:
echo "Hello Wolrd"
^Wolrd^World
# Output: echo "Hello World"
Managing History
Clear Current Session History (-c)
history -c
Delete Specific Line (-d)
Remove a specific usage (e.g., one containing a password).
history -d 501
Write History to Disk (-w)
Save current session commands to ~/.bash_history immediately.
history -w
Read History from Disk (-r)
history -r
Configuration (Environment Variables)
Add these to ~/.bashrc to customize behavior.
Add Timestamps
By default, history doesn't show WHEN a command was run.
export HISTTIMEFORMAT="%F %T "
history outputs:
1001 2026-02-14 12:00:00 ls -la
Increase Size
export HISTSIZE=10000 # Memory buffer
export HISTFILESIZE=20000 # Disk file
Ignore Duplicates and Spaces
export HISTCONTROL=ignoreboth
ignorespace: Commands starting with a space are not saved.
- ignoredups: Consecutive duplicate commands are not saved.
Ignore Specific Commands
export HISTIGNORE="ls:pwd:history:exit"
Security Best Practice
Prevent Secrets in History:
If HISTCONTROL=ignorespace is on, simply add a space before running a sensitive command.
mysqldump -pSecretPassword
Notes
- History behavior differs slightly between shells (Bash vs Zsh).
- Zsh stores history in
~/.zsh_historyand has more advanced sharing options (SHARE_HISTORY).