[linux] How can I copy the output of a command directly into my clipboard?

How can I pipe the output of a command into my clipboard and paste it back when using a terminal? For instance:

cat file | clipboard

This question is related to linux shell unix terminal clipboard

The answer is


I come from a stripped down KDE background and do not have access to xclip, xsel or the other fancy stuff. I have a TCSH Konsole to make matters worse.

Requisites: qdbus klipper xargs bash

Create a bash executable foo.sh.

#!/bin/bash
qdbus org.kde.klipper /klipper setClipboardContents "$1" > /dev/null

Note: This needs to be bash as TCSH does not support multi-line arguments.

Followed by a TCSH alias in the.cshrc.

alias clipboard xargs -0 /path/to/foo

Explanation:

xargs -0 pipes stdin into a single argument. This argument is passed to the bash executable which sends a "copy to clipboard" request to klipper using qdbus. The pipe to /dev/null is to not print the newline character returned by qdbus to the console.

Example Usage:

ls | clipboard

This copies the contents of the current folder into the clipboard.

Note: Only works as a pipe. Use the bash executable directly if you need to copy an argument.


Add this to to your ~/.bashrc:

# Now `cclip' copies and `clipp' pastes'
alias cclip='xclip -selection clipboard'
alias clipp='xclip -selection clipboard -o'

Now clipp pastes and cclip copies — but you can also do fancier stuff:

clipp | sed 's/^/    /' | cclip

↑ indents your clipboard; good for sites without stack overflow's { } button

You can add it by running this:

printf "\nalias clipp=\'xclip -selection c -o\'\n" >> ~/.bashrc
printf "\nalias cclip=\'xclip -selection c -i\'\n" >> ~/.bashrc

I've created a tool for Linux/OSX/Cygwin that is similar to some of these others but slightly unique. I call it cb and it can be found in this github gist.

In that gist I demonstrate how to do copy and paste via commandline using Linux, macOS, and Cygwin.

Linux

_copy(){
    cat | xclip -selection clipboard
}

_paste(){
    xclip -selection clipboard -o
}

macOS

_copy(){
    cat | pbcopy
}

_paste(){
    pbpaste
}

Cygwin

_copy(){
    cat > /dev/clipboard
}

_paste(){
    cat /dev/clipboard
}

Note: I originally just intended to mention this in my comment to Bob Enohp's answer. But then I realized that I should add a README to my gist. Since the gist editor doesn't offer a Markdown preview I used the answer box here and after copy/pasting it to my gist thought, "I might as well submit the answer."

cb

A leak-proof tee to the clipboard

This script is modeled after tee (see man tee).

It's like your normal copy and paste commands, but unified and able to sense when you want it to be chainable

Examples

Copy

$ date | cb
# clipboard contains: Tue Jan 24 23:00:00 EST 2017

Paste

# clipboard retained from the previous block
$ cb
Tue Jan 24 23:00:00 EST 2017
$ cb | cat
Tue Jan 24 23:00:00 EST 2017
$ cb > foo
$ cat foo
Tue Jan 24 23:00:00 EST 2017

Chaining

$ date | cb | tee updates.log
Tue Jan 24 23:11:11 EST 2017
$ cat updates.log
Tue Jan 24 23:11:11 EST 2017
# clipboard contains: Tue Jan 24 23:11:11 EST 2017

Copy via file redirect

(chronologically it made sense to demo this at the end)

# clipboard retained from the previous block
$ cb < foo
$ cb
Tue Jan 24 23:00:00 EST 2017
# note the minutes and seconds changed from 11 back to 00

Based on previous posts, I ended up with the following light-weigh alias solution that can be added to .bashrc:

if [ -n "$(type -P xclip)" ]
then
  alias xclip='xclip -selection clipboard'
  alias clipboard='if [ -p /dev/stdin ]; then xclip -in; fi; xclip -out'
fi

Examples:

# Copy
$ date | clipboard
Sat Dec 29 14:12:57 PST 2018

# Paste
$ date
Sat Dec 29 14:12:57 PST 2018

# Chain
$ date | clipboard | wc
   1       6      29

Linux & Windows (WSL)

When using the Windows Subsystem for Linux (e.g. Ubuntu/Debian on WSL) the xclip solution won't work. Instead you need to use clip.exe and powershell.exe to copy into and paste from the Windows clipboard.

.bashrc

This solution works on "real" Linux-based systems (i.e. Ubuntu, Debian) as well as on WSL systems. Just put the following code into your .bashrc:

if grep -q -i microsoft /proc/version; then
    # on WSL
    alias copy="clip.exe"
    alias paste="powershell.exe Get-Clipboard"
else
    # on "normal" linux
    alias copy="xclip -sel clip"
    alias paste="xclip -sel clip -o"
fi

How it works

The file /proc/version contains information about the currently running OS. When the system is running in WSL mode, then this file additionally contains the string Microsoft which is checked by grep.

Usage

To copy:

cat file | copy

And to paste:

paste > new_file

I am using Parcellite and xsel to copy last commit message from git to my clipboard manager (for some reason xclip does not work):

$ git log -1 --pretty=%B | xsel -i -b

I usually run this command when I have to copy my ssh-key:

cat ~/.ssh/id_rsa.pub | pbcopy

ctrl+v anywhere else.


Without using external tools, if you are connecting to the server view SSH, this is a relatively easy command:

From a Windows 7+ command prompt:

ssh user@server cat /etc/passwd | clip

This will put the content of the remote file to your local clipboard.

(The command requires running Pageant for the key, or it will ask you for a password.)


On OS X, use pbcopy; pbpaste goes in the opposite direction.

pbcopy < .ssh/id_rsa.pub

Just to cover an edge case:) and because the question title asks (at least now) how to copy the output of a command directly to clipboard.

Often times I find it useful to copy the output of the command after it was already executed and I don’t want to or can’t execute the command again.

For this scenario, we can either use gdm or a similar mouse utility and select using the mouse. apt-get install gdm and then either the right click or the Cntrl+Shift+c and Cntrl+Shift+v combinations for copy and paste in the terminal

Or, which is the preferred method for me (as the mouse cannot select properly inside one pane when you have multiple panes side by side and you need to select more than one line), using tmux we can copy into the tmux buffer using the standard [ , space , move to select , enter or you can select a block of code. Also this is particularly useful when you are inside one of the lanes of the cli multiplexer like tmux AND you need to select a bunch of text, but not the line numbers (my vim setup renders line numbers)

After this you can use the command:

tmux save-buffer - | xclip -i

You can of course alias it to something you like or bind directly in the tmux configuration file

This is just to give you a conceptual answer to cover this edge case when it’s not possible to execute the command again. If you need more specific code examples, let me know

Cheers


In Linux with xclip installed:

xclip -selection clipboard < file


For mac this is an example way to copy (into clipboard) paste (from clipboard) using command line

Copy the result of pwd command to clipboard as

$ pwd | pbcopy

Use the content in the clipboard as

$ cd $(pbpaste)

on Wayland xcopy doesn't seem to work, use wl-clipboard instead. e.g. on fedora

sudo dnf install wl-clipboard

tree | wl-copy

wl-paste > file

For those using bash installed on their windows system (known as Windows Subsystem for Linux (WSL)), attempting xclip will give an error:

Error: Can't open display: (null)

Instead, recall that linux subsystem has access to windows executables. It's possible to use clip.exe like

echo hello | clip.exe

which allows you to use the paste command (ctrl-v).


I wrote this little script that takes the guess work out of the copy/paste commands.

The Linux version of the script relies on xclip being already installed in your system. The script is called clipboard.

#!/bin/bash
# Linux version
# Use this script to pipe in/out of the clipboard
#
# Usage: someapp | clipboard     # Pipe someapp's output into clipboard
#        clipboard | someapp     # Pipe clipboard's content into someapp
#

if command -v xclip 1>/dev/null; then
    if [[ -p /dev/stdin ]] ; then
        # stdin is a pipe
        # stdin -> clipboard
        xclip -i -selection clipboard
    else
        # stdin is not a pipe
        # clipboard -> stdout
        xclip -o -selection clipboard
    fi
else
    echo "Remember to install xclip"
fi

The OS X version of the script relies on pbcopy and pbpaste which are preinstalled on all Macs.

#!/bin/bash
# OS X version
# Use this script to pipe in/out of the clipboard
#
# Usage: someapp | clipboard     # Pipe someapp's output into clipboard
#        clipboard | someapp     # Pipe clipboard's content into someapp
#

if [[ -p /dev/stdin ]] ; then
    # stdin is a pipe
    # stdin -> clipboard
    pbcopy
else
    # stdin is not a pipe
    # clipboard -> stdout
    pbpaste
fi

Using the script is very simple since you simply pipe in or out of clipboard as shown in these two examples.

$ cat file | clipboard

$ clipboard | less

I made a small tool providing similar functionality, without using xclip or xsel. stdout is copied to a clipboard and can be pasted again in the terminal. See:

https://sourceforge.net/projects/commandlinecopypaste/

Note, that this tool does not need an X-session. The clipboard can just be used within the terminal and has not to be pasted by Ctrl+V or middle-mouse-click into other X-windows.


Examples related to linux

grep's at sign caught as whitespace How to prevent Google Colab from disconnecting? "E: Unable to locate package python-pip" on Ubuntu 18.04 How to upgrade Python version to 3.7? Install Qt on Ubuntu Get first line of a shell command's output Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running? Run bash command on jenkins pipeline How to uninstall an older PHP version from centOS7 How to update-alternatives to Python 3 without breaking apt?

Examples related to shell

Comparing a variable with a string python not working when redirecting from bash script Get first line of a shell command's output How to run shell script file using nodejs? Run bash command on jenkins pipeline Way to create multiline comments in Bash? How to do multiline shell script in Ansible How to check if a file exists in a shell script How to check if an environment variable exists and get its value? Curl to return http status code along with the response docker entrypoint running bash script gets "permission denied"

Examples related to unix

Docker CE on RHEL - Requires: container-selinux >= 2.9 What does `set -x` do? How to find files modified in last x minutes (find -mmin does not work as expected) sudo: npm: command not found How to sort a file in-place How to read a .properties file which contains keys that have a period character using Shell script gpg decryption fails with no secret key error Loop through a comma-separated shell variable Best way to find os name and version in Unix/Linux platform Resource u'tokenizers/punkt/english.pickle' not found

Examples related to terminal

Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools) Can't compile C program on a Mac after upgrade to Mojave Flutter command not found VSCode Change Default Terminal How to switch Python versions in Terminal? How to open the terminal in Atom? Color theme for VS Code integrated terminal How to edit a text file in my terminal How to open google chrome from terminal? Switch between python 2.7 and python 3.5 on Mac OS X

Examples related to clipboard

In reactJS, how to copy text to clipboard? Copy output of a JavaScript variable to the clipboard Leave out quotes when copying from cell How to Copy Text to Clip Board in Android? How does Trello access the user's clipboard? Copying a rsa public key to clipboard Excel VBA code to copy a specific string to clipboard How to make vim paste from (and copy to) system's clipboard? Python script to copy text to clipboard Copy to Clipboard for all Browsers using javascript