histexpand
Execute commands from history using event designators
TLDR
Run the previous command as root (!! is replaced by the previous command)
Run a command with the last argument of the previous command
Run a command with the first argument of the previous command
Run the Nth command of the history
Run the command n lines back in the history
Run the most recent command containing string
Run the previous command, replacing string1 with string2
Perform a history expansion, but print the command that would be run instead of actually running it
SYNOPSIS
!event:modifier
PARAMETERS
!n
Refer to command line n.
!-n
Refer to the current command line minus n.
!!
Refer to the previous command.
!string
Refer to the most recent command starting with string.
?string?
Refer to the most recent command containing string.
^string1^string2^
Quick substitution: Repeat the previous command, replacing string1 with string2.
event:s/old/new/
Substitute old with new in the event.
*modifiers*
A list of modifiers applicable to history events, such as: h (remove the filename), t (remove all but the tail), r (remove file extension), e (remove all but the extension), p (print the new command but do not execute it) , q (quote the substituted words), x (escape the substituted words).
DESCRIPTION
histexpand, often accessed implicitly through shell history expansion, provides a mechanism to recall and re-execute or modify previously executed commands. This feature dramatically enhances command-line efficiency by reducing redundant typing and facilitating complex command construction. The shell automatically expands history references (typically beginning with '!' or '^') into their corresponding commands before execution.
History expansion is enabled by default in interactive shells like bash. Disabling it will cause the history characters to be treated as regular characters.
histexpand is not a standalone executable but is rather part of the shell's built-in functionality. It is therefore usually used implicitly and not directly invoked as a separate command.
CAVEATS
History expansion can lead to unexpected behavior if not used carefully, especially with complex modifications or substitutions. Always review the expanded command (using the 'p' modifier) before execution to avoid errors.
USAGE EXAMPLES
- !!: Executes the previous command again.
- !vi: Executes the last command that started with 'vi'.
- !-2: Executes the command two commands ago.
- ^old^new^: Replaces the first occurrence of 'old' with 'new' in the previous command.
- !!:p: Prints the previous command without executing it. Useful for verifying complex expansions.
HISTORY
History expansion is a fundamental feature of interactive shells and has been present in various forms since the early days of Unix. It was designed to improve command-line usability and efficiency. Over time, different shells have implemented slightly different variations of history expansion, but the core principles remain consistent.