LinuxCommandLibrary

histexpand

Execute commands from history using event designators

TLDR

Run the previous command as root (!! is replaced by the previous command)

$ sudo !!
copy


Run a command with the last argument of the previous command
$ [command] !$
copy


Run a command with the first argument of the previous command
$ [command] !^
copy


Run the Nth command of the history
$ ![n]
copy


Run the command n lines back in the history
$ !-[n]
copy


Run the most recent command containing string
$ !?[string]?
copy


Run the previous command, replacing string1 with string2
$ ^[string1]^[string2]^
copy


Perform a history expansion, but print the command that would be run instead of actually running it
$ [!-n]:p
copy

SYNOPSIS

shopt [-s | -u] histexpand

PARAMETERS

-s
    Enable (set) the histexpand option

-u
    Disable (unset) the histexpand option

-p
    Print shopt commands to recreate current settings

-q
    Quiet mode: exit status indicates if option is set

-o
    Fail if optionname invalid (restricted shells)

DESCRIPTION

The histexpand is a Bash shell option that controls history expansion, allowing interpretation of special characters like ! and ^ on input lines to recall and modify previous commands from the history list.

When enabled, Bash scans each line for history expansion before executing it. Common expansions include:
!!: repeats the previous command.
!n: runs history line n.
!-n: runs nth line backward.
!string: executes most recent command starting with string.
?string?: most recent containing string.
^old^new^: quick substitution in last command.

Enable with shopt -s histexpand; disable via shopt -u histexpand. Default is on for interactive non-login shells. Useful for efficient command-line workflows but risky in scripts, as unescaped ! in strings or regex can trigger unintended expansion.

Expansions can be quoted to prevent, e.g., '!cmd'. Related options: histverify (edits before execute), cmdhist (multi-line as one). Enhances productivity in interactive sessions.

CAVEATS

Can break scripts with literal ! (e.g., in echo '!'; use single quotes). Conflicts with some regex/awk patterns. Disabled by default in login shells.

COMMON EXPANSIONS

!!: last cmd
!$:p: last arg (physical)
!^: first arg of last
!$: last arg of last
> !ls: word after ls

TOGGLING

shopt | grep histexpand (check status)
set +H (disable, old syntax)
set -H (enable)

HISTORY

Introduced in Bash 2.0 (1996), inspired by csh(1) history substitution. Evolved with shopt in Bash 3.0+ for granular control. Widely used in interactive shells; POSIX excludes history expansion.

SEE ALSO

shopt(1), bash(1), history(1), fc(1)

Copied to clipboard