Command line Clipboard for macOS, Cygwin, and Linux

25 Mar

I use the command line a lot, even though I am on a graphical user-interface (GUI) on Windows, macOS, or Linux. And since I’m lazy, I write a lot of scripts to perform repetitive tasks. I stumbled across macOS commands that allow command line programs to copy/paste between the clipboard that we’re so used to using.

macOS pbpaste and pbcopy

macOS has two commands, pbpaste and pbcopy, which “paste” from the pasteboard to stdout and copies from stdin to the pasteboard, respectively.macOS calls their clipboard a “pasteboard”, so the pb… prefix makes sense.  For the command-line, these will only transfer text content. With these commands, then, you can pipe or redirect content as you would with any other command-line filter.

An example which would use both these commands; say, you are in your browser and want to copy the URL from your browser and use it in a command on the command-line, after copying the URL from the browser, you could run a command like:

curl `pbpaste` | pbcopy

The clipboard/pasteboard then contains the output of the curl command of the URL, previously held in the clipboard. You can paste the content into a text editor to see the raw output returned by the URL. (For the uninitiated, those single-quotes (`) are backwards single quotes).


For Linux, install the xclip command:

sudo apt install xclip

Then, define the aliases to mimic the macOS commands:

if type xclip &>/dev/null; then
  alias pbcopy='xclip -sel clip'
  alias pbpaste='xclip -sel clilp -o'


On Windows, I use Cygwin for consistent command line capability with macOS and Linux. Having found pbpaste and pbcopy on macOS, I figured similar functionality in Cygwin; but it works differently. They implement a clipboard device at /dev/clipboard. We can create a couple of aliases to make the device act like the macOS commands:

if [ -e /dev/clipboard ]; then
  alias pbcopy='cat >/dev/clipboard'
  alias pbpaste='cat /dev/clipboard'

With those settings, you can use copy/paste commands in the same fashion as in macOS and write scripts that will work in both environments.

3/25/2023 — This post was originally published Dec 3, 2013 and updated to include the Linux solution.


Tags: , , , , , , , , , , , , ,

%d bloggers like this: