
If you spend a lot of time at the shell prompt, recording shell history can save time and typing. But there are a few annoyances with history, if left unmodified: History records duplicate commands, and multiple shell instances can clobber each other’s history. Both complications are easily overcome. Add two lines to your .bashrc:
export HISTCONTROL=ignoreboth
shopt -s histappend
The first line removes consecutive duplicate commands from your shell history. If you want to remove all duplicates independent of sequence, change ignoreboth
to erasedups
. The second line appends a shell’s history to your history file when the shell exits (more on shopt). By default, the Bash history file is named (yes, a dot file) ~/.bash_history. You can change its location by setting (yes, an environment variable) HISTFILE. If you want to save a shell’s most recent 10,000 commands in a history file with 100,000 entries, add export HISTSIZE=10000 HISTFILESIZE=100000
to your shell startup file. To see a shell’s history, type history
at any prompt.
Saving a history of commands is of little use if you cannot recall it. That’s the purpose of the shell !
, or bang, operator:
!!
(“bang bang”) repeats the last command in its entirety.
!:0
is the name of the previous command.
!^
is the first argument of the previous command. !:2
, !:3
, and so on, ending with !$
are the second, third, and eventually the last argument of the previous command.
!*
is all the arguments of the last command, except the command name.
!n
repeats the command numbered n
in history.
!handle
repeats the last command that begins with the string of characters in handle
. For example, !ca
would repeat the last command that began with the characters ca
, such as cat README
.
!?handle
repeats the last command that contains the string of characters in handle
. For example, !?READ
would also matchcat README
.
^original^substitution
replaces the first occurrence of original
with substitution
. For example, if the previous command was cat README
, the command ^README^license.txt
would yield a new command cat license.txt
.
!:gs/original/substitution
replaces all occurrences of original
with substitution
. (!:gs
means “global substitution.”)
!-2
is the penultimate command, !-3
is third most recent command, and so on.
- You can even combine history expressions to yield sigil soup such as
!-2:0 -R !^ !-3:2
, which would expand to the command name of the penultimate command, followed by -R
, the first argument of the previous command, and the second argument of the third most recent command. To make such cryptic commands more readable, you can expand history references as you type. Type the command bind Space:magic-space
at any prompt, or add it to a startup file to bind the Space key to the function magic-space, which expands history substitutions inline.
Quick tip: Add a space before a command and it won’t be saved in history.