Terminal and the Clipboard

Continuing in my informal series of Terminal articles, I’d like to visit two tools that help interact from the shell to a particular part of the macOS UI: the clipboard.

The clipboard is the ‘place’ where macOS stores anything you cut (⌘X) or copy (⌘C). Later the system reads from the clipboard (and possibly converts the data) when you paste (⌘V).

Terminal can trivially interact with the clipboard. You can select text in the Terminal and copy it, and then paste it elsewhere, you can also paste text in the command prompt itself.

(This is useful when you read a great iBook with many Terminal commands. You can simply copy the command from the iBook text and paste into Terminal.)

There are however, two commands, specific to macOS that connect the clipboard closer to other shell commands.

pbcopy will take the contents of stdin (usually text, but could be any stream of data) and put them in the clipboard. So, anything you pipe into pbcopy will end up in the clipboard, so you can paste it into a different application.

(NeXTSTEP was the operating system that Mac OS X was originally based on. What was called the ‘clipboard’ in Mac OS was called ‘pasteboard’ in NeXTSTEP. While all references visible to the user where changed to the Mac OS naming, you still find the old NeXTSTEP names in the ‘innards’ of macOS, hence pbcopy and pbpaste.)


# easier than open, select all, copy
$ cat ideas.txt | pbcopy
# converts Word Doc to plain text and puts it in the clipboard
$ textutil -convert txt MyBook.docx -stdout | pbcopy
$ ipconfig getifaddr en0 | pbcopy
$ system_profiler SPHardwareDataType SPSoftwareDataType | pbcopy
$ uuidgen | pbcopy

I use the last command a lot when I need UUIDs for custom configuration profiles. It is much easier to pipe the output directly into the clipboard, than to select and copy the output.

One downside of this it, that you cannot see what is piped into the clipboard. You can easily make the new clipboard contents visible by typing pbpaste as the next command:

$ uuidgen | pbcopy
$ pbpaste


$ uuidgen | pbcopy; pbpaste

(Several UUIDs were wasted writing this article.)

pbpaste is the counterpart to pbcopy. pbpaste will take the contents of the clipboard, and if they are plain text write them to stdout. That alone can be useful when you want to visualize the clipboard but gets more powerful when you pipe or substitute it into other unix commands.


# after copying the output of uuidgen
$ plutil -replace PayloadUUID -string $(pbpaste) MyConfigProfile.mobileconfig
# copy an html snippet from somewhere or
$ echo '<a href="https://scriptingosx.com">Scripting OS X</a>' | pbcopy
# then
$ pbpaste | textutil -stdin -format html -convert rtf -stdout | pbcopy

This last command will convert an HTML snippet into rich text (rtf).

Published by


Mac Admin, Consultant, and Author