Copy command to system clipboard

May 30, 2018

In Bash you can copy the previous command to the system clipboard directly from the command line, and have it be correctly quoted, using

$ echo !!:q | xsel --input --clipboard

This is very useful for sharing or embedding complex commands. Consider this example command that includes quotation marks:

$ echo 'foo bar'
foo bar
$ echo !!:q | xsel -ib
echo 'echo '\''foo bar'\''' | xsel -ib

The first command, in its entirety, is the command we’re interested in copying. In the second command, the !! history expansion event designator selects the previously executed command, and the q modifier wraps the command in quotation marks, escaping characters as necessary. Wrapping the command in quotation marks turns it into a single argument to the second echo, which pipes it into xsel’s standard input. Although it is not obvious from any of the output in the example, the clipboard ends up containing echo 'foo bar' exactly.

You might have xclip(1) instead of xsel(1), in which case you’ll need to pass different options, and on macOS you will probably want to use pbcopy(1).

Tags: bash

Back to posts