xsel - access X selection from command line

xsel is a quick hack to give access to the X selection from the command line. You can paste stuff from the X selection to stdout and copy stuff from stdin to X selection. A few examples:

xsel -p | less            # pastes the current X selection to less
xsel --paste | less       # same as above

echo puppa | xsel -c      # 'puppa' is now the current X selection
echo puppa | xsel --copy  # same as above
xsel -c "puppa"           # same as above

echo puppa | xsel -m      # 'puppa' merged to the current X selection
echo puppa | xsel --merge # same as above
xsel -m "puppa"           # same as above

The above examples should also give you complete understanding of the xsel syntax ;).

Further options:

xsel -c -display host3:0.0 "puppa"   #Use X server on host3:0.0
xsel -c -s CLIPBOARD "puppa"         #Use CLIPBOARD selection rather than PRIMARY
                                     #You may use PRIMARY, SECONDARY or
                                     #CLIPBOARD - also abbreviations
                                     #P,p,S,s,C and c are valid.
xsel -c --selection CLIPBOARD "puppa" #Same as -s.

Note that the X selection model has no concept of selection buffer on the server. Rather, the client that holds the current selection makes it available to the other clients and has to wait until someone requests it. Hence, xsel forks and serves the selection requests until someone else claims the selection.

xsel.c is completely based on the Xfree86 xcutsel.c. Its author, Ralph Swick, deserves more credit than I do.

What is it good for?

I originally began implementing this to able to select a word in X (in any application) and get the Finnish-English/English-Finnish translation for it. I've put the following hacks in the Enlightenment shortcuts configuration:

and so on. (I modified gmessage to exit on esc key press, and make selecting text possible. The diff is available below. You can use standard xmessage as well.)

You could also do something like
locate file | xsel -c
to get a large file listing into any application via X selection.

Download

To compile: gcc xsel.c -O2 -o xsel -lX11 -lXt -lXaw -L/usr/X11R6/lib/
gcc `gtk-config --cflags` -O6 gmessage.c -o gmessage `gtk-config --libs`
(Too lazy to hack up a Makefile).

Versions

Bugs

Xsel sometimes opens a small window that is not always visible. With my configuration, it never shows up, so I'm not eager enough to figure out how to get rid of it.

Contact

v@iki.fi