I signed the Hope Accord.
30 June 2023

Copying command output to the clipboard on Linux

To copy the output of a command to the clipboard in Linux you can use the following command:

Example

echo string | xclip -selection clipboard

string (plus a newline) will now be available on the main clipboard. To strip out the newline, use echo -n.

Setup

Requires xclip, a command-line utility for working with the clipboard.

sudo apt install xclip

Script

I use the following script to strip the trailing newline only if the string is single-line:

(Saved in ~/bin as copy-input-to-clipboard).

#!/bin/bash

str=$(</dev/stdin)

lines=$(echo "$str" | wc -l)

function clipboard {
	xclip -selection clipboard
}

if [ $lines -eq "1" ]; then
	echo -n "$str" | clipboard
else
	echo "$str" | clipboard
fi

c alias

To make this available as the more concise c, put the following line in your aliases/bashrc file:

alias c='xclip -selection clipboard'

or

alias c='copy-input-to-clipboard'

Note: the -selection clipboard option indicates copying to the main clipboard as opposed to the middle-click one.