Accessing xorg clipboard from command line

Top

In this article I'm going to share a simple bash function that makes dealing with system clipboard easier on linux:

clb () { TMP='/tmp/.clb.tmp' if [[ $1 = 'e' ]] then clb > $TMP $EDITOR $TMP cat $TMP | clb rm $TMP elif [[ -t 0 ]] then xsel -b -o else xsel -b -i fi }

You need to install xsel on your system.

Usage

  • It automatically determines whether it's supposed to output the current clipboard or overwrite the clipboard based on its location in the pipeline:

    clb | rg '^//' # Search clipboard for comments cat program.cc | rg '^//' | clb # Copy all comments in a file clb | sed 's/C++/Rust/g' | clb # modify clipboard contents
  • It will open the clipboard content in your EDITOR if invoked as clb e. Clipboard will be updated when you exit the editor.