# List all previous commands
history
# Clear the history, useful if you entered a password by accident
history -c
# Expands to line n of bash history
!n
# Expands to last command
!!
# Expands to last command starting with "text"
!text
# Expands to last command containing "text"
!?text
# Expands to command n lines ago
!-n
# Expands to last command with first occurrence of "foo" replaced by "bar"
^foo^bar^
# Expands to the current command
!#
These are separated by :
from the event designator they refer to. The colon can be omitted if the word designator doesn't start with a number: !^
is the same as !:^
.
# Expands to the first argument of the most recent command
!^
# Expands to the last argument of the most recent command (short for !!:$)
!$
# Expands to the third argument of the most recent command
!:3
# Expands to arguments x through y (inclusive) of the last command
# x and y can be numbers or the anchor characters ^ $
!:x-y
# Expands to all words of the last command except the 0th
# Equivalent to :^-$
!*
These modify the preceding event or word designator.
# Replacement in the expansion using sed syntax
# Allows flags before the s and alternate separators
:s/foo/bar/ #substitutes bar for first occurrence of foo
:gs|foo|bar| #substitutes bar for all foo
# Remove leading path from last argument ("tail")
:t
# Remove trailing path from last argument ("head")
:h
# Remove file extension from last argument
:r
If the Bash variable HISTCONTROL
contains either ignorespace
or ignoreboth
(or, alternatively, HISTIGNORE
contains the pattern [ ]*
), you can prevent your commands from being stored in Bash history by prepending them with a space:
# This command won't be saved in the history
foo
# This command will be saved
bar