RSS
 

Command line clipboard in OSX and Cygwin

03 Dec

I use the command line a lot, even though I am on a graphical user-interface like Windows or OSX. And since I’m lazy, I write a lot of scripts to perform repetitive tasks. The downside of command-line is that there is no standard way to interact with GUI features. I stumbled across a command in OSX, recently that allows command line programs to copy/paste between the clipboard that we’re so used to using.

OSX pbpaste and pbcopy

OSX has two commands, pbpaste and pbcopy, which “paste” from the pasteboard to stdout and copies from stdin to the pasteboard, respectively (OSX calls their clipboard the “pasteboard”).  For the command-line, these will only transfer text content, naturally. With these commands, then, you can pipe or redirect content as you would with any other command-line filter.

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

Then paste into a text editor to see the raw output returned by the URL. (For the uninitiated, those single-quotes (`) are backwards single quotes).

Windows and Cygwin

On Windows, I use Cygwin. This provides the same kind of command line capability as OSX and Linux, so rather than learning an operating system specific command-line syntax, I use Cygwin on Windows for consistency with other systems. Having found pbpaste and pbcopy, I figured (and hoped) there was similar functionality in Cygwin. There is, but it works differently. Instead, they implement a clipboard device at /dev/clipboard. So, it isn’t a command, but we can create a couple of aliases to make the device act like it:

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

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

 

Tags: , , , , , , , , ,

  • Brilliant! I haven’t been on Cygwin for about a year now, but I like to keep it in mind in the highly unlikely (but entirely possible) event I find myself working on a Windows box. 😀

    Thanks for this!

 
%d bloggers like this: