I’ve been using this great tip from Sean Coates for years now on my remote Linux servers. It allows you to simulate the pbcopy
command (which copies piped text to the OS X clipboard) on remote SSH servers, but copies to your local clipboard instead. I’ve primarily been using OS X servers for a while now, though, and it took a few changes to get it working.
The trick uses netcat (nc
, which I think is included in the standard OS X distribution) to pipe text over an SSH connection to a local listener that passes it to pbcopy
. The arguments for netcat are slightly different on OS X, though. It also makes the assumption that you don’t already have the pbcopy
command on the server. If the server is a Mac, you do, and it would be a pity to override that. Here are solutions to both problems.
If you’re interested in trying this, first follow Sean’s instructions for the basic setup. Create the launchd listener and set up SSH forwarding in ~/.ssh/config
. Note that once you set up the forwarding of port 2224, you’ll sometimes get a warning about forwarding failing when logging into some servers. This is harmless.
When it comes time to create the shell script on the remote machine, create one called /usr/local/bin/rpbcopy
instead, with the contents below:
#!/bin/bash
[ -n "$SSH_CLIENT" ] && SESSION_TYPE="remote"
if [[ $SESSION_TYPE == "remote" ]]; then
cat | nc -c localhost 2224
else
cat | pbcopy
fi
CopyMake it executable (chmod a+x /usr/local/bin/rpbcopy
). Then, in your remote ~/.bash_profile
, add the line:
alias pbcopy="/usr/local/bin/rpbcopy"
CopyThat will replace the default pbcopy command with the script above, which checks whether you’re in an SSH session and runs nc
or the original pbcopy
accordingly.
Note that the argument -q1
in Sean’s version is invalid on for this setup. It needs to be -c
in BSD (OS X), which closes the connection when STDIN reaches EOF (end of file). That simple change and you’re good to go.
Instead of the if statement in the shell script, you could also check for the SSH session (using the same check for $SSH_CLIENT
) in your .bash_profile
and only alias pbcopy
if you’re logged in remotely. Your choice.
Now, when you’re logged in on the remote OS X system over SSH, you can type cat filename|pbcopy
or pipe the output of a command to pbcopy
and it will show up on your local clipboard. It’s the same result you’d expect if you were just working in Terminal locally, so it requires no change of habits. Handy stuff.