How can I copy the output of a command directly into my clipboard?
Asked Answered
D

25

845

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
Dollydolman answered 27/2, 2011 at 2:10 Comment(4)
possible duplicate of Pipe to/from ClipboardBipinnate
possible duplicate of superuser.com/questions/104981/…Bromley
I just asked a related question since I can't get xclip working when logging into Ubuntu from Git Bash on Windows: https://mcmap.net/q/22426/-how-can-i-copy-the-contents-of-a-file-directly-into-my-windows-clipboard-when-i-39-m-running-the-command-on-a-remote-linux-machine-via-ssh-in-git-bash/470749Arrival
Save file contents to clip board. apt install xclip and cat file | xclip -sel clipAmoritta
D
912

One way of doing it follows:

  1. Install xclip, such as:

    sudo apt-get install xclip

  2. Pipe the output into xclip to be copied into the clipboard:

    cat file | xclip

  3. Paste the text you just copied into a X application:

    xclip -o

To paste somewhere else other than an X application, such as a text area of a web page in a browser window, use:

cat file | xclip -selection clipboard

Consider creating an alias:

alias "c=xclip"
alias "v=xclip -o"

To see how useful this is, imagine I want to open my current path in a new terminal window (there may be other ways of doing it like Ctrl+T on some systems, but this is just for illustration purposes):

Terminal 1:
pwd | c

Terminal 2:
cd `v`

Notice the ` ` around v. This executes v as a command first and then substitutes it in-place for cd to use.

Only copy the content to the X clipboard

cat file | xclip
Dollydolman answered 27/2, 2011 at 2:11 Comment(14)
"cat file | xclip" only copy the content to the 'X' clipboard, if you want to paste somewhere else other than a 'X' application, try this one: "cat file | xclip -selection clipboard"Relate
Your choice of handle is appropriate!Microbe
If you want to remove the newline character so that you can directly paste and edit the result of "pwd | c", you can do "pwd | tr -d '\n' | xclip -selection c"Iodate
also define alias "cs=xclip -selection clipboard" and alias "vs=xclip -o -selection clipboard" to make copying/pasting from system clipboard easierSprig
xclip fileName works on my Ubuntu Trusty 14.04. Also, xclip -selection c works for normal copy of Control-C. The equivalent of Control-V is xclip -o -selection cBromley
Wouldn't the syntax of aliasses be alias a="b -c" instead of alias "a=b -c"? That's what I read on ubuntuusers, but apparently noone here notices it...Harquebusier
Its not available in RHEL.Militarist
I am not sure but I am getting following error Error: Can't open display: (null) @DollydolmanSoftfinned
cat file | ... There we go again.Angi
no need for cat and pipelines : xclip filePhotocathode
@alper, In WSL, instead of xclip use clip.exe. Check this: https://mcmap.net/q/12901/-error-can-39-t-open-display-null-when-using-xclip-to-copy-ssh-public-key-closedLinter
@SebastiánVásquez I am not using Windows I cannot run clip.exeSoftfinned
cd v`` says zsh: command not found: vSoftfinned
I created a tool here github.com/Ahmed7fathi/copycatSparry
T
308

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

pbcopy < .ssh/id_rsa.pub
Tontine answered 27/2, 2011 at 3:5 Comment(10)
Yups! Just like this for ex: pbcopy < .ssh/id_rsa.pubMailable
doesn't work for command output tho - e.g. pbcopy < git merge-base master some-branchBroadus
if you're using tmux, it won't work unless you reattach your session: superuser.com/a/413233/146254Haematoblast
you can also use cat, if you already work with it: cat file.txt | pbcopyChiefly
I know the comment is 5 years old, but in case someone stumbles on to this in the future, to use with command output, do git merge-base master some-branch | pbcopyExerciser
If you don't want a newline at the end of the copied content: cat file | xargs echo -n | pbcopyOrton
pbcopy < [some alias command] doesn't work. But [alias command] | pbcopy does work. Thanks @Orton for newline fix. That helped my need.Kola
pay attention to pbcopy to not confuse < with > because with this > you will paste into the file, possibly erasing it's contentsLetter
When did OS X become linux?!? Or do we just ignore what the op wanted?Isoprene
@Isoprene I have a Mac and I was looking for how to copy to the clipboard from terminal and this is the 1st question I landed on. Since the terminals are similar, they share similar questions and invite similar answers.Mouldon
E
113

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." If you would like to discuss functionality/bugs it would probably be best to do that in the comments for the gist on github.

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
Evaevacuant answered 25/1, 2017 at 4:51 Comment(7)
This worked perfect for me to copy a command output to the clipboard in terminal on macOS, thanks!Footed
One solution to rule 'em all! Big thanks, worked for me on MacOS - i'll test it on Linux tooValuer
It hangs while doing the chaining example in Ubuntu 18.04. The tests show the same behaviour, tried running cb --test and it hangs on the changing test.Maryannamaryanne
Thanks for the feedback @PabloAdames! I got some comments on the gist about it having when run over ssh. Are you running it on a local Ubuntu 18.04 or over ssh?Evaevacuant
@bruno-bronosky I found the reported hanging in Ubuntu 18.04 as the local operating systemMaryannamaryanne
cb does not work on current mac os @JoshuaDyck, you mean pbcopy which works on mac.Pathway
Yeah, it doesn't seem to work anymore on macOSFooted
V
54

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
Vercingetorix answered 18/10, 2013 at 20:10 Comment(6)
I use the names pbcopy and pbpaste on Linux so it works for both Linux and OS X.Hostetler
To make the script work globally in ubuntu: * Save it at ~/.scripts/clipboard * Make it executable chmod +x ~/.scripts/clipboard for bash: * add export PATH=$PATH:~/.scripts to the end of ~/.bashrc for fish: * add set PATH ~/.scripts $PATH to ~/.config/fish/fish.config If any of the files or folders don't already exist just create them.Gelasias
You can also wrap this script as a function clipboard(){ ... } and paste it into .bashrcRonrona
This is very similar to the one I made, but I allow chaining like date | cb | tee -a updates.log. That would send the date command output to the clipboard and pass it along to the tee -a command which appends it to a file and passes it along to stdout. But it's like a "leak-proof tee to the clipboard" because if you just do date | cb you get no output. And finally it also does cb > file.txt gist.github.com/RichardBronosky/…Evaevacuant
One suggestion - strip the trailing newline character to avoid executing the command on pasting(e.g. if copy-pasting a path). I do that by modifying the command xclip -i -selection clipboard to xargs echo -n | xclip -i -selection clipboardChilcote
Actually the command above does not work well if the thing you want to copy to clipboard is multi line. Here is what I did to fix this: cat - | perl -pe 'chomp if eof' | xclip -selection clipboardChilcote
C
52

Native Solution with .bashrc Script

Linux, macOS, Windows (WSL/CYGWIN)

Each of those systems use its own tool to incorporate the clipboard functionality into the command line interface (CLI). This means, when using for example the Ubuntu CLI on Windows Subsystem for Linux (WSL) the usual xclip solution won't work. The same holds true for macOS.

The following table provides an overview for the copy/paste tools needed on the different systems:

OS Copy Paste
WSL clip.exe powershell.exe Get-Clipboard
CYGWIN > /dev/clipboard cat /dev/clipboard
macOS pbcopy pbpaste
Linux xclip -sel clip xclip -sel clip -o

Unified .bashrc Solution

Just put the following code into your ~/.bashrc to enable the usage of copy and paste on all systems. The solution works on "normal" Linux systems (i.e. Ubuntu, Debian) as well as on WSL and macOS:

if grep -q -i microsoft /proc/version; then
  # on WSL: version contains the string "microsoft"
  alias copy="clip.exe"
  alias paste="powershell.exe Get-Clipboard"
elif grep -q -i cygwin $(uname -a); then
  # on CYGWIN: uname contains the string "cygwin"
  alias copy="/dev/clipboard"
  alias paste="cat /dev/clipboard"
elif [[ ! -r /proc/version ]]; then
  # on MAC: version is not readable at all
  alias copy="pbcopy"
  alias paste="pbpaste"
else
  # on "normal" linux
  alias copy="xclip -sel clip"
  alias paste="xclip -sel clip -o"
fi

Usage on ALL systems

To copy:

# pipe
echo "hello world" | copy

# or for direct file input
copy < file

To paste:

paste > file
Calash answered 22/6, 2020 at 15:18 Comment(1)
This should be a ZSH plugin!Sphenoid
B
27

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
Boltonia answered 25/2, 2015 at 23:34 Comment(1)
Give a usage example pleasePrehistory
J
21

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 by your machine's shortcut for paste or in a command as in below

$ cd $(pbpaste)
Jaddan answered 18/9, 2019 at 13:12 Comment(0)
D
11

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.)

Dressmaker answered 5/12, 2014 at 15:30 Comment(3)
@AfshinMoazami, the title and the question itself is generic, Only the tags hint for unix system, and my answer covers the case when you try to get the date FROM a unix server TO a Windows machine, which may be useful future readers.Dressmaker
Upvoted because yes, useful to Windows admins who only have Powershell to play with locally (although now with LSW actually functional, I can drop into bash directly from Powershell and do my *nixy things from there).Arcane
Its working on DOS prompt as well as git bash on windows 10 i.e. echo Hello World | clipRosaniline
B
11

macOS:

your_command_which_gives_output | pbcopy

WSL / GNU/Linux (requires the xclip package):

your_command_which_gives_output | xclip -sel clip

Git Bash on Windows:

your_command_which_gives_output | clip
Blackford answered 18/3, 2021 at 9:32 Comment(0)
D
8

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
Dithyrambic answered 14/4, 2016 at 13:32 Comment(1)
-i is the default. I use a lot for eg xsel -b | sort | uniq -c | sort -rn | xsel -bIncognizant
M
7

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
Medea answered 25/3, 2020 at 13:7 Comment(0)
P
6

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

cat ~/.ssh/id_rsa.pub | pbcopy

cmd+v or ctrl+v anywhere else.

Papilionaceous answered 19/2, 2020 at 15:8 Comment(1)
I also found this is more natural on OS X, the up-voted one: pbcopy < command didn't work for me.Steerage
P
5

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.

Premedical answered 11/11, 2013 at 20:8 Comment(0)
C
5

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).

Callean answered 30/6, 2018 at 0:15 Comment(1)
Do note that if an xserver (such as vcxsvr or xming) is installed on windows, a display is up and xclipboard is running, you can actually use xclip seemlessly.Interlay
S
4

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.

Settlings answered 15/1, 2019 at 17:49 Comment(0)
L
3

In Linux with xclip installed:

xclip -selection clipboard < file

Leighton answered 28/1, 2016 at 19:59 Comment(0)
D
2

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
Dozen answered 29/12, 2018 at 21:32 Comment(0)
W
2

Here's great solution for Arch Linux users. Install xsel with pacman, like:

sudo pacman -S xsel

Create alias in ~/.bashrc file, like:

alias pbcopy='xsel --clipboard --input'
alias pbpaste='xsel --clipboard --output'

reload your terminal with source:

source ~/.bashrc

use it like mentions above:

cat your_file.txt | pbcopy

fyi, good practice stroing all of the aliases in ~/.aliases and call it in .bashrc file

Wallache answered 2/4, 2021 at 19:15 Comment(0)
L
2

2021 Answer

If you were searching for an answer to the question, "How do I copy the output of one command into my clipboard to use for my next command?" like I was, then this solution works great as a Mac user.

In my example, I wanted to simply copy the output of which postgres so I could simply paste it in my next command.

I solved this by piping my first command which postgres with pbcopy.

which postgres | pbcopy

Then I could simply command + V which produced my desired result:

/usr/local/bin/postgres
Lewes answered 23/4, 2021 at 15:56 Comment(0)
E
1

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

Ehrlich answered 24/3, 2019 at 18:42 Comment(0)
M
1

There is a method that works without installing xclip/xsel, usefull if you don't have sudo access.

You just need vimx installed, that is VIM +clipboard support. You can find it in most distros.

Save this script as ~/copy_to_clipboard.sh,

#!/bin/sh
if [ -z "$1" ]
  then
  str=" "
else
  str=$1
fi

vimx -u NONE -U NONE -N -c "let @a=\".\"" -c "let @*= \"$str\" " -c " put a " -c "sleep 2" -c " q!"

give execution permission: chmod +x ~/copy_to_clipboard and call it with:

~/copy_to_clipboard.sh STRING

For some reason, you need to set a dummy @a register and paste it on temporary file. Otherwise clipboard register will not be set correctly. In the end discard temporary Vim file.

Your clipboard will be set, you can paste it with mouse middle-click

Multicolored answered 24/1, 2022 at 12:42 Comment(1)
Thank you, it works for me. Not suitable for copying arbitrary data though, due to problematic escapes and command line argument limitations.Petrozavodsk
P
0

With sudo privileges:

echo '#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
from tkinter import Tk
r = Tk()
r.withdraw()
r.clipboard_clear()
data = ""
for i in sys.stdin:
        data = data + i
r.clipboard_append(data)
r.update()
r.destroy()' | sudo tee /usr/bin/copy > /dev/null
sudo chmod +x /usr/bin/copy

Alternatively without sudo privileges (only for one user):

echo '#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
from tkinter import Tk
r = Tk()
r.withdraw()
r.clipboard_clear()
data = ""
for i in sys.stdin:
        data = data + i
r.clipboard_append(data)
r.update()
r.destroy()' > ~/.local/bin/copy
chmod +x ~/.local/bin/copy

Usage:

echo "hi" | copy
Pepita answered 10/4, 2021 at 15:0 Comment(4)
That looks convoluted, what are the benefits compared to existing answers which use xsel?Poul
you dont have to install anythingPepita
I would say that a single standalone xsel binary is nothing compared to the huge python3 framework. Some people might have xsel already installed, while not having python3. On top of that, your python script depends on the tkinter, which might not be installed as well. If the motivation of this answer to provide something with fewer dependencies, then I think it's exact opposite.Poul
On most linux systems is python already installed and tkinter is also includet.Pepita
S
0

I created a tool here. It depends on the xclip package.

Sparry answered 5/5, 2022 at 1:51 Comment(0)
C
0

For macOS, this is my custom pbcopy/pbpaste wrapper within my AWK library, so I could:

  • "copy" anything directly from AWK to the clipboard (while still processing other stuff),

  • directly "paste into" AWK,

  • have extra function aliases for those coming from Windows paradigm


function  copy2pb(_) { return cmdC(_) }
function    CtrlC(_) { return cmdC(_) }
function cmdC(_, __) {
                        # 1st argument: item to copy out
                        # 2nd argument: optional custom trailing byte

    printf("%s%s",_, __~/^[\0\12-\15]+$/ \
                                     ? __ \
            :        __~/^[Yyn]/    ?  ORS \
            : "") | (_ = " LC_ALL=C pbcopy ")
    return close(_)
}

function       pb2paste() { return cmdV() }
function          CtrlV() { return cmdV() }
function cmdV(__, ___, _) {
                            # Since this is for pasting in,
                            # any and every argument made would be ignored
    return \
    substr((___ = RS) (RS = "^$"),
    (_ = " LC_ALL=C pbpaste ") | getline __,
     -close(_) ^ (RS = ___)^sub("\n$", "", __))__
}
Caron answered 21/5, 2023 at 16:21 Comment(0)
S
-1

Here are two simple solutions with only two lines of code in each method!

No need to install additional software (and the latter may come with tons of dependencies, some of which having potentially security problems)

Note: 2nd method does not work with nano editor in Debian.

1st method:

  1. sudo printf "\n#$(date)" >> /path/intended_file
    Note: Preceeding any line with leading comment sign # does not damage any file.
  2. Open file with editor sudo gedit /path/intended_file then copy Date to clipboard inside the editor and paste it to anywhere.

2nd Method

  1. Write content of a uniqueFile file located anywhere on disk to a delete.txt file:
    sudo find / -iname 'uniqueFile' >> delete.txt
  2. Open file with text editor gedit delete.txt and copy (Ctrl-C) the highlighted desired long-long path to the clipboard from the editor. Or you can use terminal nano editor too (although does not support the "standard" Ctrl-C).
  3. Optional additional step:
    If delete.txt is already your personal log file:
    rm delete.txt or mv delete.txt memo-uniqueFile.txt
Sexivalent answered 4/8, 2021 at 10:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.