View history
history
history 20
Execute from history
!number
!-2
!!
sudo !!
Search history
Ctrl+R
Ctrl+R again
Ctrl+G
Search by string
!string
!?string
Execute and print
!number:p
!!:p
Clear history
history -c
> ~/.bash_history
Delete specific entry
history -d number
History size
HISTSIZE=10000
HISTFILESIZE=20000
Ignore duplicates
HISTCONTROL=ignoredups
HISTCONTROL=ignorespace
HISTCONTROL=ignoreboth
Ignore specific commands
HISTIGNORE="ls:cd:pwd:exit:date"
Timestamp
HISTTIMEFORMAT="%Y-%m-%d %H:%M:%S "
history
Preserve history
shopt -s histappend
PROMPT_COMMAND="history -a"
Word designators
!!:0
!!:1
!!:$
!!:*
!!:2-4
Quick substitution
^old^new
!!:gs/old/new
Previous command arguments
!$
!^
!*
Alt+.
Search history file
grep "pattern" ~/.bash_history
cat ~/.bash_history | grep ssh
Save current session
history -a
history -w
Reload history
history -r
Multiple sessions
shopt -s histappend
PROMPT_COMMAND="${PROMPT_COMMAND:+$PROMPT_COMMAND$'\n'}history -a; history -c; history -r"
Export history
history > my_commands.txt
Analyze history
history | awk '{print $2}' | sort | uniq -c | sort -rn | head -10
history | grep "$(date +%Y-%m-%d)" | cut -c 8-9 | sort | uniq -c
FC command (edit and execute)
fc
fc 100 105
fc -l
fc -s old=new 100
Keyboard shortcuts
Ctrl+R Reverse search
Ctrl+S Forward search
Ctrl+P Previous command (↑)
Ctrl+N Next command (↓)
Ctrl+A Beginning of line
Ctrl+E End of line
Ctrl+U Clear line before cursor
Ctrl+K Clear line after cursor
Alt+. Last argument
Alt+B Back one word
Alt+F Forward one word
History expansion
!!
!-n
!string
!?string?
^str1^str2
!#
Practical examples
Repeat with modification
git commit -m "message"
^commit^push
Use previous arguments
cat /very/long/path/file.txt
vim !$
Fix recent command
systemctl status nginx
sudo !!
Build on previous
cd /var/log
ls !$
Best practices
HISTSIZE=50000
HISTFILESIZE=100000
HISTCONTROL=ignoreboth
HISTIGNORE="ls:ll:cd:pwd:clear:history"
HISTTIMEFORMAT="%F %T "
shopt -s histappend
PROMPT_COMMAND="history -a"
Troubleshooting
History not saving
ls -la ~/.bash_history
chmod 600 ~/.bash_history
echo $HISTFILE
Lost history
cat ~/.bash_history
cp ~/.bash_history.bak ~/.bash_history