history – display command history

history command
history command

history displays previously executed commands. Essential for recalling and reusing commands.

Synopsis

history [N]
history [OPTIONS]

Examples

Show recent commands

$ history
  501  ls -la
  502  cd /var/log
  503  grep error syslog
  504  history

Show last N commands

$ history 10

Execute command by number

$ !502
cd /var/log

Execute last command

$ !!
# Useful: sudo !!

Execute last command starting with…

$ !grep
grep error syslog

Search history

# Ctrl+R for interactive search
(reverse-i-search)`grep': grep error syslog

Show command without executing

$ !502:p
cd /var/log

History Expansion

SyntaxMeaning
!!Last command
!NCommand number N
!-NN commands ago
!stringLast command starting with string
!?stringLast command containing string
^old^newRepeat last, replace old with new

Argument Expansion

SyntaxMeaning
!$Last argument of last command
!^First argument of last command
!*All arguments of last command
!:NNth argument of last command

Examples

$ cat /etc/passwd
$ less !$           # less /etc/passwd

$ cp file1 file2 file3 /backup/
$ ls !*             # ls file1 file2 file3 /backup/

$ echo one two three
$ echo !:2          # echo two

Clear History

# Clear current session
$ history -c

# Clear and delete history file
$ history -c && history -w

# Delete specific entry
$ history -d 502

History Settings

# In ~/.bashrc
export HISTSIZE=10000          # Commands in memory
export HISTFILESIZE=20000      # Commands in file
export HISTCONTROL=ignoreboth  # Ignore duplicates and spaces
export HISTIGNORE="ls:cd:pwd"  # Don't record these
export HISTTIMEFORMAT="%F %T " # Add timestamps

Tips

  • Ctrl+R: Interactive reverse search (most useful!)
  • Don’t log secrets: Prefix with space to skip history (if HISTCONTROL includes ignorespace)
  • Append history: shopt -s histappend to preserve across sessions
  • Share history: PROMPT_COMMAND="history -a; history -n" for multiple terminals

See Also

  • fc — Edit and re-execute commands
  • alias — Create command shortcuts

Tutorials