xsel
’s default behaviour depends on whether its input or output is connected to a terminal, so redirecting to and from files typically does the right thing. As mentioned by codeforester, the solution in your case is to run
xsel -b > file
You can make your intent explicit by adding -o
(when outputting the contents of the clipboard) or -i
(when inputting to the clipboard). Without these options, if xsel
’s context is indeterminate (i.e. neither standard input or standard output are connected to a terminal), it behaves in -o
mode: xsel -b < /dev/null > file
works as you’d expect, but xsel -b < file > /dev/null
doesn’t.
You can also use xclip
to copy the clipboard’s contents to a file:
xclip -sel c -o > file
xclip
can additionally request specific versions of the clipboard’s contents (known as targets), depending on the selection’s owner; for example, if you copied text from a web browser, you could retrieve it as HTML using
xclip -sel -c -o -t text/html > file
The special TARGETS
target will list the available targets:
xclip -sel -c -o -t TARGETS