ubuntu, updated

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:

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

WhatCommand
Show historyhistory
Last 20 commandshistory 20
Searchhistory | grep ssh or Ctrl+R
Delete one entry (number from history)history -d 523
Clear this session’s historyhistory -c
Clear everything, incl. the filehistory -c && history -w
Write the session to the file nowhistory -w
Don’t save this session at allunset HISTFILE
Run a command without saving itstart 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

  1. Leading space: export TOKEN=abc is not saved. Works because Ubuntu sets HISTCONTROL=ignoreboth (= ignore space-prefixed and duplicate lines).
  2. Let the tool ask: mysql -p without a password prompts for it. Same for sudo, ssh, passwd.
  3. Read secrets from a file or variable: curl --netrc-file ~/.netrc ..., or read -s TOKEN to 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) or auditd.

§ home
~/knubertus/home/
1,1 Top