X

Make use of the clipboard for OS X commands

OS X includes Terminal commands that can pipe and retrieve data from the clipboard.

Topher Kessler MacFixIt Editor
Topher, an avid Mac user for the past 15 years, has been a contributing author to MacFixIt since the spring of 2008. One of his passions is troubleshooting Mac problems and making the best use of Macs and Apple hardware at home and in the workplace.
Topher Kessler
2 min read

When running commands in the OS X Terminal, you might find the need to save or redirect the output for use elsewhere. Common methods for doing this are to save the output in a text file, or to pipe it directly to another command. This way you can parse and manipulate the data output to get the results you want, using a number of approaches to do so.

If you decide to redirect output to files in order to save them, you will have to perform some cleanup routines at a later point to remove the files. While the use of direct piping prevents file accumulation and clutter, it can also be somewhat limiting as it does not store one command's output so it can be sent to multiple commands.

Of course if you are managing complex routines that parse and manage output from multiple commands, then using file redirection is perhaps the most convenient solution. However, if you are only manipulating the output of one command, then you can make use of Apple's "pbcopy" and "pbpaste" commands to store this output in the clipboard, instead of using files or direct piping.

As their names suggest, pbcopy will store data sent to it in the clipboard, and pbpaste will retrieve this data from the clipboard. For example, the following command routine will echo the text "Testing" to the clipboard, and then retrieve it from the clipboard:

echo Testing | pbcopy
pbpaste

Now to retrieve the stored text, you simply need to use the "pbpaste" command again, and it will be retrieved. While this may seem unnecessary for small bits of text that can be saved as Terminal variables, it can be useful for more complex output such as saving the redirected contents of a file, or the table output of activity and process viewers, or disk management tools.

In addition to being a storage medium for passing data between commands, the pbcopy command itself can be used as an interface between the command line and GUI-based applications. For instance, if you are writing a paper in Word or Pages and wish to include the output of a command or two, you can run the commands in Terminal and then select and copy the output, or you can simply pipe the output of the commands to the "pbcopy" command, and then go to Word or Pages and use Command-V to paste the copied text to your paper.



Questions? Comments? Have a fix? Post them below or e-mail us!
Be sure to check us out on Twitter and the CNET Mac forums.