July 29, 2023

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.


  1. From the man page.↩︎

  2. in the words of a GNU/Linux contributor.↩︎


command-line interface (cli) personal computing wiki gnu linux trisquel history office applications shell literacy

No affiliate links, no analytics, no tracking, no cookies. This work © 2016-2024 by yctct is licensed under CC BY-ND 4.0 .   about me   contact me   all entries & tags   FAQ   GPG public key

GPG fingerprint: 2E0F FB60 7FEF 11D0 FB45 4DDC E979 E52A 7036 7A88