Access Your OS X Clipboard from the Command Line

There may be times when you need to access whatever is on your clipboard in a Terminal; maybe a particularly long URL for example.  And, there may be times when you want to put things on to the clipboard from a Terminal.

Reading the Clipboard

As it’s going to be text on the clipboard (even if it’s an image, it’ll just be the file name if you use this command), you can access it using the command pbpaste:

$ pbpaste

So in this case, I have the text “” on my clipboard, but what if I want to access that from a string of commands?  (I’m using curl as an example from another post)

$ curl -Is `pbpaste` | head -n1

By placing ` ` around the pbpaste command, it will run, and whatever it returns will be used instead.  So, the above command in this instance will actually run:

$ curl -Is | head -n1

Of course, you may want to just run a few stats on the contents of your clipboards, and you can also do this using the wc command I posted about.  You can run pbpaste and pipe it through the wc command as follows:

pbpaste | wc -w

This will return the amount of words currently on the clipboard.

Writing to the Clipboard

But what if you want to get content onto the clipboard?  We use the pbcopy command.

So if I want to get the contents of a text file onto the clipboard, I could cat the file and pipe it through to pbcopy as follows:

cat myfile.txt | pbcopy

Anything which gets passed to pbcopy this way, will be on the clipboard.

Likewise, if I want to put a single line of text onto the clipboard, I could use the echo command:

echo "I want this on the clipboard" | pbcopy

As this is the normal clipboard, this content is available using the normal paste commands and of course pbpaste.

So if you ever find yourself needing to use the clipboard from a Terminal, then pbpaste and pbcopy are the commands to do it!