# 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 --clipboard

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

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

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. The final command dumps the contents of the clipboard selection : `echo 'foo bar'` , as desired.

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 ergonomics

Back to posts