8

I need a way to get/copy data from clipboard to a variable in Bash. Is there such one?

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255

2 Answers2

12

Strictly speaking, no. Bash itself has no awareness of your clipboard.

However, there are some command line utilities for interacting with the clipboard, but they vary from OS to OS.

On Linux, the command xsel can be used to interact with the X clipboard. If you want to write to the clipboard do some_command | xsel -ib and if you want to dump the contents to stdout use xsel -ob. This command is not usually installed by default, but is probably available through your package manager.

On OS X, the corresponding commands are pbcopy (for writing to) and pbpaste (for reading from).

To read into the variable a in bash, you can do

a=`xsel -ob`

or

a=`pbpaste`

as appropriate.

Greg Nisbet
  • 3,076
5

You can use the xclip command to access the clipboards if it is installed.

xclip -o # Print the primary selection (highlighted text)
xclip -o -selection clipboard # Print the regular clipboard (ctrl-c from gui applications)

You can set the value of a variable to the output of a command in bash using backticks e.g.

clip=`xclip -o -selection clipboard`

To set the value of $clip to the x11 clipboard

Matt
  • 287