Your shell remembers the commands you type, so you do not have to retype them. This lesson describes bash. Other shells such as zsh and fish have history too, with differences.
Looking at history
$ history
501 cd /var/log
502 ls -l
503 historyEach line has a number and the command. Give a number to show only the most recent entries: history 10.
Using the keyboard
The Up arrow brings back the previous command, and Down moves forward again. You can edit the line before pressing Enter.
Press Ctrl+R and start typing to search backwards through history:
(reverse-i-search)`log': cd /var/logPress Ctrl+R again for an older match, Enter to run it, or Ctrl+G to cancel.
History expansion
Bash replaces certain ! patterns before running a line:
!!is the previous command.!502is command number 502.!lsis the most recent command starting withls.
A common use:
$ apt update
$ sudo !!
sudo apt updateBash prints the expanded line and then runs it. Be careful: it runs immediately. Add :p, as in !502:p, to print without running.
Where it is saved
Commands are kept in memory during the session and are normally written to ~/.bash_history when the shell exits. So two open terminals may not see each other's latest commands. The HISTSIZE variable controls how many are remembered.
Removing entries
history -d 502 deletes one entry and history -c clears the list in the current shell. history -c by itself does not rewrite the saved file there and then. To write the cleared list to the file, follow it with history -w.
Because history is stored as plain text, avoid typing passwords as part of a command. Some distributions set HISTCONTROL so that a line starting with a space is not recorded, but do not rely on it without checking:
$ echo $HISTCONTROL
ignorebothTry it
- Run
history 5. - Use the Up arrow to recall a command and edit it.
- Press Ctrl+R and search for part of an old command.
- Print a numbered entry with
!N:p, replacingNwith its number.
Check your understanding
history
All 5 sections ยท no timer
Unlimited retries
Questions from every section are combined into one assessment. Answer them all correctly to complete the article.
Your completion saves in this browser. Sign in to sync it to your account.