July 26, 2023

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.


  1. From the man page.↩︎

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


command-line interface (cli) personal computing wiki gnu linux trisquel xclip 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