Interacting with the clipboard from terminal using xclip

Introduction

In this guide I will be showing you how you can interact with the clipboard from the terminal. The focus of this will be how you can do things like copy the contents of a file (or output from a program) directly into memory and also how you can paste directly into a file from the terminal.

Requirements

In order to follow this guide, you will need the following:

Getting setup

First step is to make sure your package manager has an up to date list of packages

sudo apt update

We can then install xclip

sudo apt install xclip

Usage

Once its installed, we are able to use xclip to interract with our clipboard.

To copy, we can do this using this command:

xclip -selection c

To paste, we can do this

xclip -selection c -o

bashrc alias

To make our lives easier and stop us having to write out all of that, we can add an alias to our bashrc file. Add the following to the end of our ~/.bashrc file

alias copy="xclip -selection c"
alias pasta="xclip -selection c -o"

Save the file and exit. We can then source the bashrc to load in our new aliases

source ~/.bashrc

We should now have an alias for copy (copy) and paste (pasta). Feel free to change these to whatever you like.

Example uses

Here are a few examples using our copy pasta aliases

# Copy the contents of input.txt to the clipboard
cat input.txt | copy
# Paste into file named output.txt. 
pasta > output.txt