Copy Remote File Contents to Local System Clipboard with OSC 52

Published on 2026-09-02

I do most of my development on a remote Debian machine. Often I ask an agent to produce a Markdown or HTML report, and then I want its contents on my Mac clipboard immediately.

If the file were on my local Mac, I could simply do: cat filename | pbcopy. But that kind of thing wouldn’t work when the file is on a remote machine.

The simple solution is just running cat filename on the remote machine and then copying the output by selecting it with a mouse/trackpad. But if the contents of the file are more than a couple of lines, that’s annoying.

Good old OSC 52 is the best solution in such cases:

copy() {
    local encoded
    encoded=$(base64 -w0 -- "$1") || return 1
    printf '\033]52;c;%s\a' "$encoded"
}

Add the function to ~/.bashrc, start a new shell, and run:

copy report.md

The command encodes the file as Base64 and wraps it in an OSC 52 escape sequence. SSH sends that sequence back to the terminal running on the local machine. The terminal recognizes it and writes the decoded text to the system clipboard.

There is no clipboard tool running on the remote machine. The local terminal does the copying.

All we need is for the terminal to support OSC 52 and permit clipboard access. Most modern terminals do. I use Ghostty and of course it does.

Using it inside tmux

If you use tmux on the remote machine like I do, then you just need a little bit of modification:

Add the following to the tmux settings:

# ~/.tmux.conf
set -s set-clipboard external

Then extend the function:

copy() {
    if [[ -n ${TMUX:-} ]]; then
        tmux load-buffer -w -- "$1"
        return
    fi

    local encoded
    encoded=$(base64 -w0 -- "$1") || return 1
    printf '\033]52;c;%s\a' "$encoded"
}

Reload tmux, and the copy command would work both inside and outside it:

copy report.html

The file’s contents are now on the local Mac clipboard, ready to paste anywhere. Fuck mouse selection and fuck file transfer over SSH and fuck opening the remote server in VS Code.