How to copy and paste into and out of a terminal

The problem

In the Linux desktop environment, there are two methods of copying and pasting. These are known as selections in the X world and are:

The primary selection (highlight-to-copy and middle-click-to-paste) works well in most situations although some desktop applications do not accept pasting from the primary selection. I’m looking at you LibreOffice until very recently. They are not common and will always accept pasting from the clipboard selection.

The situation when I have experienced consistent problems is when I work in a terminal utility such as the undisputed champion of text editors nano. The problems that I’ve encountered are:

  1. Copying an entire document that is longer than the current window can display. This prevents highlighting the entire contents of the file preventing copying to either the primary or clipboard selections.
  2. CTRL-C-to-copy won’t work in a terminal as CTRL-C is a break. Also, CTRL-V is not assigned.

The solutions - Copying to and from the clipboard selection (CTRL+C-to-copy CTRL+V-to-paste)

The standard short cuts, CTRL+C and CTRL+V wont work but there are alternative shortcuts assigned to copy and past from the clipboard selection into a terminal. They are:


The solutions - Copying large documents to the clipboard

When your file is too large to highlight so you can’t copy it into either selection use the xclip utility. xclip takes standard input or a file and places it into a chosen selection.

For example, if you have a text file called report.txt and you want to put its contents into the primary selection (Highlight-to-copy and mouse-middle-click-to-paste) the following xclip command will work:

xclip -selection primary report.txt

If you want to use the clipboard selection (CTRL+C-to-copy CTRL+V-to-paste) instead then use:

xclip -selection clipboard report.txt

xclip will also accept standard input if what you want to copy something that isn’t in a file e.g.:

ps auxf | xclip -selection clipboard

Pasting isn’t usually a problem but xclip will also print the contents of a selection to standard output (stdout) with the -o option e.g.:

xclip -selection clipboard -o