Copy and paste are one of the most popular operations of our daily life. Generally, the muse right-click is used to copy and paste with a GUI or desktop environment. But as Linux is a geeky operating system some users prefer the command line interface where they also require the copy and paste operation. But how can we integrate the GUI or Desktop clipboard with the command line interface? The xclip command is the first choice for copy paste and clipboard access operations from the command line interface.
The xclip command mainly uses the standard input and standard output in order to read and write with the X server to communicate with the Desktop environment clipboard. The xclip command can also interact with the contents of the file, command input, and output.
Install xclip Command
The xclip command is provided by all major Linux distributions.
Ubuntu, Debian, Mint Kali:
$ sudo apt install xclip
Fedora, CentOS, RHEL:
$ sudo dnf install xclip
Copy File Contents To Clipboard From Command Line
One of the most popular use cases for the xclip command is copying the specified file contents into the clipboard from the command line interface. The file name or path should be specified to the xclip command as a parameter where the xclip command reads this file contents and copy to the Clipboard.
$ xclip names.txt
If the current user privileges do not provide the ability to read a given file the sudo command can be used to read the file contents into the clipboard. But this clipboard is only available for the root user or normal user with the sudo privilege.
$ sudo xclip /var/log/syslog
Copy Specified Lines From File To Clipboard
Other commands like
head can be used to get the first or last part of the file and copy it to the clipboard using the xclip command.
$ tail -n 15 commands.txt | xclip -sel
Print Clipboard Contents To The Command Line
The clipboard content can be also printed into the command line interface by using the -o option.
$ xclip -o
Redirect Clipboard Content Into A File
The xclip command can be also used to redirect the clipboard content into a file. This can be done with the > bash shell redirection like below. In the following example, we will redirect or put the clipboard content into the file named clipboard.txt.
$ xclip -o > clipboard.txt
Redirect Another Command Output To Clipboard
Different commands output can be used later by pulling from the clipboard. But first, the command output should be redirected into the clipboard which can be used later. The pipe operator of the Linux bash can be used to redirect the command output to the xclip command.
$ update | xclip $ ls -la | xclip $ cat /etc/passwd | xclip