Clipboard Piping with `pbcopy`/`pbpaste` on Any OS
MacOS has two incredibly useful commands: pbcopy and pbpaste. They let you
pipe text directly to and from the system clipboard from the terminal. Want to
feed clipboard contents into an LLM? pbpaste | llm "summarize this". Want to
grab command output and paste it elsewhere? jq 'keys' file.json | pbcopy.
These commands were such a delight to stumble upon on my work-provided Macbook
Pro. I missed them when I had to hand back the machine upon the conclusion of
the role, so I ended up writing some aliases that would bring these commands to
all my regular platforms. Every platform has some method to interact with the
clipboard, but the beauty of pbcopy and pbpaste is a simple software design
philosophy:
Here’s what I added to my ~/.bashrc to satisfy my muscle memory:
pbpaste() {
if [ -n "${DISPLAY}" ] && which xclip &>/dev/null; then
xclip -selection c -o
elif which wl-paste &>/dev/null; then
wl-paste
elif which pbpaste &>/dev/null; then
command pbpaste
else
cat /tmp/clipboard
fi
}
pbcopy() {
if [ -n "${DISPLAY}" ] && which xclip &>/dev/null; then
xclip -selection c
elif which wl-copy &>/dev/null; then
wl-copy
elif which pbcopy &>/dev/null; then
command pbcopy
else
cat - > /tmp/clipboard
fi
}These functions detect your environment and route clipboard operations to the right tool:
pbpastechecks for X11 (xclip), then Wayland (wl-paste), then macOS, and finally falls back to reading from/tmp/clipboardpbcopydoes the same in reverse:xclip,wl-copy, macOSpbcopy, or writes to/tmp/clipboard
These work exactly as I want them:
- Cross-platform abstraction: One interface works across macOS, X11, Waylan, and any system via a file fallback.
- Pipe-friendly: Functions accept standard input and output, integrating seamlessly with Unix pipes for chaining commands.
- Fallback to
/tmp/clipboard: A simple file stores clipboard data as a last resort, ensuring functionality on any system — even without a graphical environment.
This means you can write scripts using pbcopy/pbpaste and they’ll work
anywhere, without having to remember which clipboard tool each OS uses. A small
addition that makes terminal life more pleasant across machines.
#command-line-tools #pbcopy #macos #productivity #terminal #cross-platform #shell-aliases #bash #pbpaste #cli #clipboard #linux #workflow
Reply to this post by email blZake@proZbableodyssey.blog (remove Z characters) ↪
Comments
Leave a comment
Markdown is supported. Your email is private and only used if you'd like a reply.