Copy a command from the shell history to the clipboard
To copy a command from the shell history to the clipboard run:
$ echo [event designator]:q | xclip -i
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 option -i, short for -in, tells xclip to read (copy) text into the clipboard from standard input, which is piped from the previous command. That is what the vertical bar | (called ‘pipe’) is for.
So, with all this we can for example do
$ echo !!:q | xclip -i
which will copy the last command ran to the clipboard. Or
$ echo !-2:q | xclip -i
which will copy the penultimate command ran to the clipboard.
If you can’t count how far back in history is the command you want to copy to the clipboard, run:
$ history | less
and check the number of the line of the command you need to copy , then run:
$ echo !n:q | xclip -i
n refers to command line on line n of the shell history.
Then you can paste the command using Shift + Insert.
If you need to install xclip, run:
$ sudo apt install xclip
You can also copy a command from the shell history to a file.
To learn more about event designators run $ man history then type /Event Designators; about xclip run $ man xclip.
xclip is copyleft-licensed and is maintained by Peter Åstrand.
command-line interface (cli) personal computing wiki gnu linux trisquel xclip history office applications shell literacy