Piping the Output of a Command to the Clipboard

This is a simple post about how to pipe the output of a command to the clipboard on Ubuntu, i.e., a way to get the output of a command such as

readlink -f 2007_000027.jpg  # gets the canonical path

to the clipboard without using the mouse. If you just want the command, skip ahead to the bash alias.

The Problem

When designing computer vision (and other) algorithms, one often encounters strange edge cases — situations where an algorithm that has successfully processed thousands of images fails spectacularly on one particular input. Generally, a quick check of the problem image in an image viewer like feh or an interactive shell like IPython can identify some of the more common bugs (corrupted image data, integer overflow/underflow, etc.).

Getting a specific image into IPython, for example, requires first selecting the filepath with the mouse (drag-select or double-click), copying with Ctrl-Shift-C, and then loading it with something like:

img = cv2.imread('<Ctrl-Shift-V here>')

Without starting a flame war (Is using a mouse less efficient?), I find the keyboard to be significantly faster than the mouse for frequently-used commands in a keyboard-friendly environment, like vim and i3. As a result, I want to achieve the above without using the mouse.

The Solution

A quick Google search reveals that xclip is a good place to start. A good idea, however, is first to strip any trailing newline from the input to ensure that it is not interpreted as a command. Thus, the full command becomes

readlink -f 2007_000027.jpg | xargs echo -n | xclip -selection clipboard

This gets the canonical path to the file 2007_000027.jpg, strips the trailing newline, and sends the result to the clipboard.

As a Bash Alias

We can make this more convenient by adding the following line to ~/.bash_aliases:

alias xclip='xargs echo -n | xclip -selection clipboard'

Now, we can easily load a given image by simply piping its canonical path to the clipboard. For example,

readlink -f 2007_000027.jpg | xclip

gets us

/media/hdd/hendrik/datasets/pascal-2011/TrainVal/VOCdevkit/VOC2011/JPEGImages/2007_000027.jpg

with Ctrl-Shift-V. No mouse involved.