Using the Mac clipboard from a shell
I assume most people that will read this probably already know this but I often forget it's a thing so here we go, a blog post.
Once in a while I need to copy or paste data while using a shell command in the terminal. Usually it's pasting some small bit of text to the shell from another app and CMD-V works fine. What if you need to paste more than a small bit of text though? Or maybe you need to write a script and take advantage of the clipboard for steps between commands? The Mac has commands for that: pbcopy
and pbpaste
.
pbpaste
will grab whatever is in the clipboard (assuming it's some text form - plain text or rich text) and send it to the standard output. So if you've got some text in the clipboard you can see it with:
pbpaste | cat
Sometimes though you need to copy the output of something to the clipboard to paste outside of the terminal. pbcopy
to the rescue. So for instance maybe you just generated an ssh key and need to copy the public key part to the clipboard to paste into a web form (yes I just did this which triggered this post):
cat id_rsa.pub | pbcopy
pbcopy
takes some text from standard input and places it in the clipboard.
As always there are more details that are available (like which clipboard to use, there is more than one) that I won't go into here. man pbcopy
or man pbpaste
will show the full options for both commands.
I should be using these commands more often since my work life as a developer often has me moving text around between apps and the terminal. Maybe having written this post will prod me into using them more. They can make life a lot easier for certain tasks!