Wednesday, August 27, 2025

pbcopy from linux shell

Working across Mac, Windows, and Linux via SSH? Ever wished you could pbcopy from within a remote SSH session? Add this "one-liner" to your ~/.bashrc or ~/.profile:
pbcopy() {
 printf "\033]52;c;%s\033\\" "$(cat | base64 -w0)"
}
If you use tmux you will need a bit more:
pbcopy() {
  if [ -n "$TMUX" ] && command -v tmux >/dev/null 2>&1; then
    # Read stdin into tmux buffer and also copy to system clipboard via OSC 52
    tmux load-buffer -w -
  else
    # Direct OSC 52 for non-tmux shells
    # Portable base64: avoid line wraps
    printf '\033]52;c;%s\007' "$(base64 | tr -d '\n')"
  fi
}
To support it inside screen:
pbcopy () {
    if [ -n "$TMUX" ] && command -v tmux > /dev/null 2>&1; then
        tmux load-buffer -w -;
    elif [ -n "$STY" ]; then
        # inside GNU screen: wrap OSC 52 in screen's DCS passthrough (\eP ... \e\\)
        # so screen forwards it to the outer terminal instead of swallowing it
        printf '\033P\033]52;c;%s\007\033\\' "$(base64 | tr -d '\n')";
    else
        printf '\033]52;c;%s\007' "$(base64 | tr -d '\n')";
    fi
}

No comments:

Followers