ProbableOdyssey | Blake Cook

Clipboard Piping with `pbcopy`/`pbpaste` on Any OS

· 2 min read · 346 words

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:

Don’t make me think

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:

These work exactly as I want them:

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.