I use the command line a lot, even though I am on a graphical user-interface like Windows or macOS. 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 macOS, recently that allows 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 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:
[bash light=”true”]
curl `pbpaste` | pbcopy
[/bash]
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 macOS 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:
[bash light=”true”]
if [ -e /dev/clipboard ]; then
alias pbcopy=’cat >/dev/clipboard’
alias pbpaste=’cat /dev/clipboard’
fi
[/bash]
With those settings, you can use pbcopy/paste commands in the same fashion as in macOS and write scripts that will work in both environments.