What does the history command do and how do you rerun previous commands?
history prints a numbered list of the commands you've run; you re-run them with !-expansions like !! (last command) or !503 (command number 503).
Each line in history has a number, and the ! prefix is how you point back at one. The shell expands the reference before running, so !503 literally becomes whatever command #503 was:
$ history
501 cd /var/log
503 cat messages
| Syntax | Re-runs… |
|---|---|
!! |
the last command |
!503 |
command #503 |
!grep |
the last command that started with "grep" |
!?error |
the last command containing "error" |
!$ |
(not a command) the last argument of the previous line |
The everyday hero is sudo !!: you run a command, hit "Permission denied," and re-run it with root privileges without retyping a thing.
sudo !! # repeat the last command, now with sudo
cat !$ # cat whatever the previous command's last argument was
You can tune how much is remembered in ~/.bashrc:
HISTSIZE=10000 # commands kept in the current session's memory
HISTFILESIZE=20000 # commands saved to ~/.bash_history across logins
Gotcha: history is only flushed to the file when the shell exits, so commands from a session that's still open (or one that crashed) may not appear in another shell yet. Tip: for finding a past command, Ctrl+R is usually faster than scrolling history | grep.