Keyboard and mouse photo by Martin Garrido via Unsplash

Keyboard and mouse photo by Martin Garrido via Unsplash

Usually, one would copy-paste by selecting something with a mouse or keyboard, and then either right-click with the mouse, or using the usual keyboard shortcuts:

  • Linux: Ctrl + C and then Ctrl + V
  • macOS: + C and then + V

to copy-paste from one window or tab to another. So why would one want to copy-paste using a command line?

Sometimes, what you want to paste is quite a bit larger than a single word or a line, and may be produced by another command-line tool, where copy-pasting its entire output is combersome and error-prone, and you’re bound to miss a few words or lines especially if you have to scroll back in the output.

On macOS, you can use the tools pbcopy and pbpaste as follows:

$ cat my-file.txt | pbcopy

and now you can paste it anywhere, e.g., using + V in another app. Or, you can use it as a temporary buffer between commands and get the output from a previous pbcopy command by using its parallel pbpaste:

$ pbpaste | grep "..."

You can also mix-and match: first copy with + C, and then paste with pbpaste.

Overall, these are very handy tools. Linux doesn’t come with these tools out-of-the-box, so how could we get the same functionality?

Turns out, these already exist, just not as single commands, but we can create aliases. In fact, there are multiple tools that implement this functionality, so we have our choice of using xclip:

alias pbcopy='xclip -selection clipboard'
alias pbpaste='xclip -selection clipboard -o'

or, alternatively, using xsel:

alias pbcopy='xsel --clipboard --input'
alias pbpaste='xsel --clipboard --output'

If you don’t have either of these tools, you can install them via your package manager, e.g., on Ubuntu, it’s as easy as:

$ sudo apt install xclip xsel

Of course, these aliases will only work for you in your interactive shells; if you want to be able to use them in scripts, you probably want to create small shell script wrappers and put them in a directory that’s in your $PATH, e.g., $HOME/bin, assuming that’s where you keep your miscellaneous tools and scripts.

Here’s a sample $HOME/bin/pbcopy:

#!/bin/sh
xsel --clipboard --input

And similarly for $HOME/bin/pbpaste:

#!/bin/sh
xsel --clipboard --output

This works on both X Window System (aka X11) as well as Wayland.

Happy copy-pasting on the command line!