History Command Guide for Bash, Sh & Zsh
Your terminal’s memory of every command.
What Is the History, and Why Use It?
The shell records every command you type into a history list, stored on disk (~/.bash_history for bash, ~/.zsh_history for zsh) and in memory. history lets you review it, re-run entries, search it, and rescue commands you already ran but can no longer remember typing.
Why Learn History?
- Typing
sudo systemctl restart nginx && systemctl status nginxtwice is a waste of life;!42runs it again. Ctrl+Rbackward-search is the single most-used keyboard shortcut in this wiki.- History is a debugging log: when something broke yesterday, the command that broke it is in there.
History is the difference between a terminal you use and a terminal that remembers for you. Learn
history,!!, andCtrl+R, and your typing drops by half.
1. Listing and Running Commands
history # numbered list of recent commands
history 20 # just the last 20
history | grep nginx # find when you touched nginx
!! # re-run the previous command
!42 # re-run command number 42
!nginx # re-run the most recent command starting with "nginx"
!$ # the last argument of the previous command
2. Searching History
Ctrl+R # start a reverse search; keep pressing to cycle
Ctrl+R, then type # narrowing the query narrows the match
Ctrl+G # abort the search
3. Controlling What Is Saved
export HISTSIZE=10000 # commands kept in memory
export HISTFILESIZE=20000 # lines saved to the file
history -d 42 # delete one entry
history -c # clear the list entirely
history -w # write the list to the file now
4. Editing the Last Command
Alt+. # insert the last argument (bash)
^nginx^docker^ # re-run last command with text swapped
Common Pitfalls
| Mistake | Fix |
|---|---|
!! re-ran something dangerous | That is what !! does — review with history first |
| History missing after a reboot | Flush it: history -a appends to the file before the session ends |
| Two terminals overwriting each other’s history | Enable histappend (zsh) / PROMPT_COMMAND history sharing (bash) |
| Can’t find an old command | history | grep pattern beats scrolling |
| Sensitive commands in the file | history -d N removes single entries; consider HISTIGNORE |
Related Pages
| Page | What It Covers |
|---|---|
| Environment Variables | HISTSIZE, HISTFILESIZE and friends |
| Aliases | Turning frequent history entries into shortcuts |
| Keyboard Shortcuts | Ctrl+R, Ctrl+G, Ctrl+C in practice |
| Shell Scripting | history -c as a scripting hygiene habit |
| bash / sh / zsh | Where each shell keeps its history file |
History Cheatsheet
| Task | Command |
|---|---|
| List history | history |
| Last N entries | history N |
| Re-run previous command | !! |
| Re-run command #N | !N |
Re-run last nginx command | !nginx |
| Reverse search | Ctrl+R |
| Delete one entry | history -d N |
| Clear all entries | history -c |
| Save to file now | history -w |
| Last argument of previous command | !$ or Alt+. |