Shell history
Where Bash keeps your command history, how to search and clear it, and why you should keep secrets out of it.
How it works
Bash remembers your commands in memory and writes them to ~/.bash_history when the shell exits. Every user (and root) has their own file. By default Ubuntu keeps the last 1000 commands in memory and 2000 in the file.
Why clear it (and why to care at all)
The history file is plain text. Everything you typed is in it, including mistakes like:
- a password in a command line (
mysql -p'Secret123',curl -u admin:pass ...) - an API token pasted into an
exportorcurlcall - internal hostnames and paths an attacker would love to know
Anyone who gets that account, a backup or root can read it. So: keep secrets out of history, and if one got in, remove it.
Cheat sheet
| What | Command |
|---|---|
| Show history | history |
| Last 20 commands | history 20 |
| Search | history | grep ssh or Ctrl+R |
Delete one entry (number from history) | history -d 523 |
| Clear this session’s history | history -c |
| Clear everything, incl. the file | history -c && history -w |
| Write the session to the file now | history -w |
| Don’t save this session at all | unset HISTFILE |
| Run a command without saving it | start it with a space |
history -c alone only clears memory. When you log out, Bash would still write the remaining session to the file, and the old file stays untouched. That’s why history -w follows, which overwrites the file with the (now empty) list.
Root has its own history: sudo -i then the same commands, or sudo truncate -s 0 /root/.bash_history.
Keep secrets out
- Leading space:
export TOKEN=abcis not saved. Works because Ubuntu setsHISTCONTROL=ignoreboth(= ignore space-prefixed and duplicate lines). - Let the tool ask:
mysql -pwithout a password prompts for it. Same forsudo,ssh,passwd. - Read secrets from a file or variable:
curl --netrc-file ~/.netrc ..., orread -s TOKENto type it hidden.
Useful settings
Add to ~/.bashrc, then source ~/.bashrc:
HISTSIZE=10000 # commands kept in memory
HISTFILESIZE=20000 # commands kept in the file
HISTTIMEFORMAT="%F %T " # show date and time in `history`
shopt -s histappend # several SSH sessions append instead of overwriting
Note: History is a convenience, not an audit log. Users can edit or delete it. For real auditing use the logs (
journalctl _COMM=sudo,/var/log/auth.log) orauditd.