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.

Also, file.txt will be created if it does not exist.

So, with all this we can for example do

$ echo !!:q  > file.txt

which will copy the last command ran to a file. Or

$ echo !-2:q > file.txt

which will copy the penultimate command ran to a file.

If you can’t count how far back in history is the command you want to copy to a file, run:

$ history | less

and check the number of the line of the command you need to copy, then run:

$ echo !n:q > file.txt

n refers to command line on line n of the shell history.

You can also copy a command from the shell history to the clipboard.

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. © 2016-2023 yctct.com. Content is licensed under CC BY-NC-SA 4.0 .