Copy the Command Line Outputs to Clipbord in Bash

Preparation

The involved tool is called xclip. So check whether the xclip had been installed or not.
If not, install it fitst:

  • Fedora:
    1
    sudo dnf install xclip
  • Ubuntu
    1
    sudo apt-get install xclip

The size of this software is only 16KB, so the install producere should be finished soon.

Usage

Copy text to clipboard

Example:

1
echo "string" | xclip -selection c

This results that the “string” is copied to the clipboard. The texts can be pasted not only in terminal, but also in other windows just using the shortcut “Ctrl + V”.

The command above is an easist example. The commands except ‘echo’ are also available.

1
cat filename | xclip -selection c

This leads that the contents of a file named “filename” is copied.

Paste to a text file

Paste the contents to a file:

1
xclip -o > helloworld.c

Nonetheless, this command is not frequently used. Because most of time, I can redirect the output to a file using echo “string” > helloworld.c .
Only when the texts are copied from other windows, may this command be a little helpful.

Simplify

The command cat filename | xclip -selection c is a little verbose. So I decide to write a bash file to simplify it.
I create a file named “fileclip” and write:

1
2
3
#!/bin/bash

cat $1 | xclip -selection c

Typing chmod 755 fileclip to change the access permission of the file.
Put this file under the folder within the $PATH. Type the $PATH in terminal to see which folders are included.

Now I can use a swift command to copy the contents of a file:

1
fileclip helloworld.c



(My first English blog actually. Hope this passage can be helpful for you.)