Copy and paste of Linux terminal command's standard output using xclip

Using xclip to simplify your workflow when working on the Linux terminal can make work more fun, exciting, and faster. This tool allows you to easily copy data from a standard input, or from one or more files and paste the data into X application.

Copy and paste of Linux terminal command's standard output using xclip
Yellow background with terminal box icon in the middle

Using xclip to simplify your workflow when working on the Linux terminal can make work more fun, exciting, and faster. This tool allows you to easily copy data from a standard input, or from one or more files and paste the data into X application. The second command-line utility we are going to use is pipes (|) that are standard in Unix systems. The pipe command is used to transfer the standard output of a command into standard input on another command in a unidirectional data stream (data flows from left to right).

Installing xclip

You will need to install xclip if you haven't already.  You can run the following command to verify if it is installed:

whereis xclip

The following commands will install xclip on the most popular types of Linux distributions.

Debian/Ubuntu

sudo apt install xclip

CentOS/RHEL/Fedora

sudo yum install xclip

Arch

sudo pacman install xclip

Copy and Paste

To copy the standard output of a command to the X clipboard as standard input  all you need is to pipe the first command to xclip with no arguments since it defaults to the -i, -in argument. If using a mouse, the copied standard input will be placed in the middle click.

command1 | xclip

To paste the text you just copied to a standard output, you add the -o, -out argument to the xclip command or use the middle click.

xclip -o

Use-Case Example

Generally these two commands are used to pipe to a file or program. Let's take a look at an example of this workflow:

  1. Pipe the standard output of our system's uptime as standard input to the X clipboard.
uptime | xclip
  1. Print as standard output of the content copied to a new file as standard input.
xclip -o > hello.txt
  1. To verify if the content was added to this new file, you can print the file to a standard output with the cat command line utility.
cat hello.txt

Paste with Right-Click

If you preferred to have the standard output of the first command on the right-click of your mouse or CTRL-V you can specify a selection with the -sel, -selection argument. The selection you will need to choose is the sec, secondary or  clip, clipboard.

command1 | xclip -sel clip
command1 | xclip -sel sec

References