Interacting With X Clipboard in Bash

Stephen Brennan • 03 August 2014

I ran across this neat trick a couple days ago. I was looking for a way to copy command output from my terminal, rather than using the clumsy selection capabilities in my terminal emulator du jour. I hit this Stack Overflow article, which introduced me to xclip, a program that lets you interface with X ‘selections’. These selections are basically text buffers in the X window system. The clipboard is one of them (the CLIPBOARD selection), and so is any text you highlight (the PRIMARY selection). The xclip program lets you use those buffers as the source or destination of a pipeline!

Unfortunately, using xclip to interface with the clipboard requires a few non-obvious parameters. You need to specify which selection you want to use. In my case, I wanted to use the clipboard, so my selection is c. The parameter -i puts text into the buffer from stdin, and the parameter -o takes text from the buffer and puts it into stdout. If you use -f with -i, it ‘filters’ the text–copies it, and then prints it to stdout. So, with these flags, you can come up with Bash equivalents for your typical cut, copy, and paste operations.

$ xclip -selection c -i    # Cut (does not filter)
$ xclip -selection c -i -f # Copy (does filter)
$ xclip -selection c -o    # Paste

Of course, with a few simple lines in your .bashrc, you can do even better. Take the keyboard shortcuts for cut, copy, and paste, and turn them into Bash aliases! (You could try to use the words cut, copy, and paste for the aliases, but paste is already a command).

$ alias x='xclip -selection c -i'
$ alias c='xclip -selection c -i -f'
$ alias v='xclip -selection c -o'

Once you have that in your .bashrc and sourced that in your terminal, you can start piping from v, and piping to c and x. There are quite a few ways you could use these commands.

I’m already finding these additions to my .bashrc to be really useful. I hope they’re useful to you!


LegalRSS

Creative Commons License

Stephen Brennan's Blog is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License