Bash – xclip works differently in interactive and non-interactive shells

bashclipboardgnome-terminalxclip

While investigating a problem described in a question at stackoverflow I simplified it down to a test case demonstrating that in non-interactive mode bash seems to clear the X system clipboard before exiting. The test opens a gnome terminal and runs a bash script in it that places (via xclip) some text in the X system clipboard. While the terminal is open, querying the clipboard returns the text that was placed in it regardless of whether bash is run in interactive or non-interactive mode. However, after the terminal is closed, the clipboard contents survives if bash was run in interactive mode, but is lost if bash was run in non-interactive mode.

$ cat xclip_test 
#!/usr/bin/env bash
set -x
gnome-terminal -x bash -i -c "echo abc|xclip -selection clipboard; sleep 3"
sleep 1
xclip -o -selection clipboard
sleep 4
xclip -o -selection clipboard
gnome-terminal -x bash -c "echo 123|xclip -selection clipboard; sleep 3"
sleep 1
xclip -o -selection clipboard
sleep 4
xclip -o -selection clipboard

$ ./xclip_test
+ gnome-terminal -x bash -i -c 'echo abc|xclip -selection clipboard; sleep 3'
+ sleep 1
+ xclip -o -selection clipboard
abc
+ sleep 4
+ xclip -o -selection clipboard
abc
+ gnome-terminal -x bash -c 'echo 123|xclip -selection clipboard; sleep 3'
+ sleep 1
+ xclip -o -selection clipboard
123
+ sleep 4
+ xclip -o -selection clipboard
Error: target STRING not available            #!!!!!!!!!!!!!

I am on Ubuntu 16.04, using default GNU bash (version 4.3.46(1)-release (x86_64-pc-linux-gnu)) with no customizations to bash rc files. I checked .bash_logout just in case and found a call to clear_console utility. However clear_console doesn't seem to deal with the clipboard; besides, the example doesn't run bash as a login shell.

Is this something having a sensible explanation?

EDIT

The problem persists when replacing gnome-terminal with xterm:

gnome-terminal -x … –> xterm -e&

Also it is not unique to bash – it is reproduced with dash, too.

Best Answer

Actually, there is no X "system clipboard". Selections in X work by two X clients cooperating: One X client claims it has an selection (primary, secondary, clipboard), and another X client that wants to paste the selection contacts the first client to receive it.

So when the first client is dead, there's no selection. I'm not sure how bash interactive mode translates to "the terminal/bash is still available to respond", however. Doing a ps may help to clear things up.

The same applies to the clipboard selection, unless you run the program xclipboard (or a similar program) at the same time, which takes over the responsibility of providing the selection. (See e.g. the wikipedia article).

There are also cut-buffers stored as properties of the root windows, which you can useto store permanent content.

Related Question