History Expansion

History expansion is a way that zsh allows you to to quickly recall previously executed commands from the current command line.

A history expansion begins with a ! (1). They may occur anywhere on a command line, but they do not nest. If you'd like to use a literal ! on the command line, quote it out. (2 , 3)

After you hit ENTER on the command line, zsh evaluates all of the history expansions before doing anything else. It then echoes the resultant command-line thus far, and continue on to other types of substitution and expansion.

(Some people like to double-check their intended history expansion before the shell processes the rest of the command line. See HIST_VERIFY on the Related Options page.)

Some Handy Tricks

Syntax

There are three parts to a history expansion: event designators, word designators (optional), and modifiers (optional). The syntax is as follows:

designator[:word][:mod1:mod2...]

Event Designators

An event designator is simply something you type on the command line that refers to an entry in the history list. There are many useful event designators, summarized below.

!
Start a history expansion, except when followed by a blank, newline, `=' or `('

!!
Refer to the previous command. By itself, this expansion repeats the previous command.

!n
Refer to command-line n.

!-n
Refer to the current command-line minus n.

!str
Refer to the most recent command starting with str

!?str[?]
Refer to the most recent command containing str

!#
Refer to the current command line typed in so far. The line is treated as if it were complete up to and including the word before the one with the !# reference.

!{...}
Insulate a history reference from adjacent characters (if necessary).

Word Designators

When making a history reference, you don't need to recover the whole command. Perhaps you only want a few words from the command, You can use a word designator to indicate which word or words of a given history entry you want included in a history reference. Simply specify an event designator from above, followed by a :, and then the word designator. (4)

Here are the various word designators that you can use:

0
The first input word (command)
n
The nth argument
^
The first argument
$
The last argument
%
The word matched by (the most recent) ?str search (5)
x-y
A range of words. x defaults to 0.
*
All of the arguments, or a null value if there are none
x*
An abbreviation for x-$
x-
Like x*, but omitting word $

Word Modifiers

These are the same set of modifiers that work on filename generation and parameter expansion. See the Modifiers page.

Syntax and Usage Notes
Related Options and Parameters