Copy a command from the shell history to a file
To copy a command from the shell history
to a file run:
$ echo [event designator]:q > file.txt
An event designator is a reference to a command line entry in the history
of the shell1. For example if you want to run the last command again, run $ !-1
or the synonym $ !!
.
The q
that comes after the event designator is a modifier which tells bash to enclose the substitution (e.g. !!) in single quotes (’) to prevent further expansion by the shell.2. Modifiers are always preceded by a colon, i.e. :
.
The >
redirection operator tells the shell to redirect the output of a command - here echo
- to a file which will be created if it does not exist.
So, with all of this in mind, we can for example run:
$ echo !!:q > file.txt
which will copy the last command in the shell history to a file. Or
$ echo !-2:q > file.txt
which will copy the penultimate command in the shell history to a file.
If you can’t count how far back in the shell history the command you want to copy to a file is, run:
$ history | tail
then find our the number (n
) of the command you want to copy to a file, then run:
$ echo !n:q > file.txt
See also:
To learn more about event designators run $ man history
then type /Event Designators
.
command-line interface (cli) personal computing wiki gnu linux trisquel history office applications shell literacy