Copying to OSX Clipboard from Remote Linux Terminal in iTerm2

Many people know about extremely useful program pbcopy that copies from stdin to Mac clipboard. You can do something like cat urls.txt | pbcopy to copy content of urls.txt to Mac clipboard. Easy and very useful.

Unfortunately when you connect to Linux box using iTerm2 you could not just call pbcopy – there is no such command in Linux and besides you are using remote box. But there is a very nice solution if you use iTerm2. iTerm2 allows terminal program to control clipboard using escape codes. So below is bash function that is analog of pbcopy on Mac. To use it add three lines below to your .bashrc file.

function pbcopy {
    base64 -w 0| xargs -0 -d "\n" -n1 -I {} bash -c "echo -ne '\e]52;;{}\e\\'"

Now if you want to copy output from some program to Mac clipboard you can just do

> cat data.txt | pbcopy 

One significant limitation is that you could not copy more than 500-600 bytes this way.

This entry was posted in linux, mac, tools, unix. Bookmark the permalink.
Joel Mellon
Joel Mellon

Don't forget to turn on "Allow clipboard access to terminal apps" in iTerm2 > Preferences > General