Pipe to/from the clipboard in a Bash script
Solution 1
2018 answer
Use clipboard-cli. It works with macOS, Windows, Linux, OpenBSD, FreeBSD, and Android without any real issues.
Install it with:
npm install -g clipboard-cli
Then you can do:
echo foo | clipboard
If you want, you can alias to cb
by putting the following in your .bashrc
, .bash_profile
, or .zshrc
:
alias cb=clipboard
Solution 2
There are a wealth of clipboards you could be dealing with. I expect you're probably a Linux user who wants to put stuff in the X Windows primary clipboard. Usually, the clipboard you want to talk to has a utility that lets you talk to it.
In the case of X, there's xclip
(and others). xclip -selection c
will send data to the clipboard that works with Ctrl + C, Ctrl + V in most applications.
If you're on Mac OS X, there's pbcopy
. E.g., cat example.txt | pbcopy
If you're in Linux terminal mode (no X) then look into gpm
or Screen which has a clipboard. Try the Screen command readreg
.
Under Windows 10+ or Cygwin, use /dev/clipboard
or clip
.
Solution 3
Make sure you are using alias xclip="xclip -selection c"
or else you won't be able to paste using Ctrl+v.
Example:
After running echo -n test | xclip
, Ctrl+v will paste test
Solution 4
Install
# You can install xclip using `apt-get`
apt-get install xclip
# or `pacman`
pacman -S xclip
# or `dnf`
dnf install xclip
If you do not have access to apt-get
nor pacman
, nor dnf
, the sources are available on sourceforge.
Set-up
Bash
In ~/.bash_aliases
, add:
alias setclip="xclip -selection c"
alias getclip="xclip -selection c -o"
Do not forget to load your new configuration using . ~/.bash_aliases
or by restarting your profile.
Fish
In ~/.config/fish/config.fish
, add:
abbr setclip "xclip -selection c"
abbr getclip "xclip -selection c -o"
Do not forget to restart your fish instance by restarting your terminal for changes to apply.
Usage
You can now use setclip
and getclip
, e.g:
$ echo foo | setclip
$ getclip
foo
Solution 5
On macOS, use the built-in pbcopy
and pbpaste
commands.
For example, if you run
cat ~/.bashrc | pbcopy
the contents of the ~/.bashrc
file will be available for pasting with the Cmd + V shortcut.
To save the current clipboard to a file, redirect the output pbpaste
to a file:
pbpaste > my_clipboard.txt
Comments
-
moinudin about 2 years
Is it possible to pipe to/from the clipboard in Bash?
Whether it is piping to/from a device handle or using an auxiliary application, I can't find anything.
For example, if
/dev/clip
was a device linking to the clipboard we could do:cat /dev/clip # Dump the contents of the clipboard cat foo > /dev/clip # Dump the contents of "foo" into the clipboard
-
Braden Best over 8 yearsI've been using
:%y+
in vim, which is vim-speak for "yank (copy) all the lines into the '+' register (the XPRIMARY
clipboard)". You can replace%
with a range if you want to be specific. But there's three caveats: 1. Now, you have to save whatever text to a file before you can copy it. This is in contrast to thexclip
command mentioned in the answers. 2. If you don't already know how to vim, this might be tedious. 3. You can only do this if a certain feature is enabled when compiling vim. If you install GVim, it should be enabled by default in both GUI and terminal instances of vim. -
HankCa about 7 years@BradenBest you should put this in as an answer. I'm in a NIX environment and was unable to install
xclip
. Your answered worked like a charm. -
Braden Best about 7 years@HankCa Okay, I posted an answer. Tell me what you think.
-
HankCa about 7 years@BradenBest its a very comprehensive answer. I just liked the
:%y+
one but ok, you've got all bases covered! Good one. -
VonC over 6 yearsAnother option: using a little perl script: no installation require. See my answer below.
-
ctrl-alt-delor over 4 yearsYou have tagged this as Linux, and Macos: MacOS does not use Linux. Do you mean Gnu/Linux with X11, Gnu/Linux with wayland, Gnu/Linux at console (no gfx), Gnu/Linux via ssh, or Mac OSX?
-
Antonio Costa over 3 yearsMy simple solution to copy, for example,
ls
output is :ls | xclip -i -selection clipboard
.
-
-
moinudin about 15 yearsI am perfectly aware of the multiple clipboards. How does this make my question any more difficult to answer?
-
glenn jackman almost 13 yearscygwin: /dev/clipboard
-
Mihai Rotaru almost 13 yearson Windows,
/dev/clipboard
also works for Msys/MinGW bash shells -
Klaas van Schelven almost 13 yearsNote that
xclip -selection c
will send data to the clipboard that works with ^C, ^V in most applications -
maep over 12 yearson newer windows versions you can just use
clip
like this:dir | clip
-
Jonah over 10 yearsHow would one go about pasting it without that command argument?
-
doug over 10 years
xclip -selection clipboard -o
-
doug over 10 yearssince I go back and forth between osx and linux a lot I have the following in my dotfiles.
alias pbcopy="xclip -selection c"
alias pbpaste="xclip -selection clipboard -o"
Hope that helps. -
ApockofFork about 10 yearsWhen I use this method it always adds in a newline character at the end of the copied text. Do you know of a way to disable or block that newline character?
-
David X about 10 years@ApockofFork,
xclip
isnt adding a newline,echo
is. Tryprintf test | xclip -i -selection clipboard
. (printf
doesnt add a newline unless you write'test\n'
.) -
Hi-Angel over 9 yearsIt is sad that GNU/Linux have no such a device as
/dev/clipboard
, and forces to install either xclip either gpm which is missing by default at least in Kubuntu (I guess in most other distros too). -
mike over 9 yearsUnder X11, there is also
xsel
which operates on the X selection by default. So you canecho hello | xsel
orxsel|wc
and so on without using a commmand-line switch. -
Christian Pietsch over 9 yearsOr use
echo -n
instead ofprintf
. -
Admin about 9 yearsIt would make sense if clipboards were standardized, probably wouldn't hurt if you could use /dev/clip1, /dev/clip2 .. /dev/clip<n> to access them, the only issue is that they are user specific and devices are system-wide. But if you make a kernel device driver that masks according to the accessing UID, it should work as expected.
-
Scz almost 9 yearsFor all other distros: you can download the source from sourceforge.net/projects/xclip
-
FractalSpace almost 9 yearsAlso, on Windows:
clip < <filename>
orecho yes | clip
-
eduncan911 over 8 years+1 Best solution! In Arch,
sudo pacman -S xclip
. But do note that.bashrc
is not the best place. I recommend the enduser read up on proper bashrc, bash_aliases and .profile files and how bash handles each. Tip: put it in .bash_aliases instead. -
tleb over 8 yearsThanks @eduncan911! :) Added the option of using the
pacman
package manager and removed the.bashrc
proposition. I know.bash_aliases
is more adapted, but the end result is the same (.bashrc
simply requires.bash_aliases
if it exists). If people want a messy system, let them have one. :) -
Shawn Erquhart over 8 yearsAs user @maep mentioned in a separate comment, newer versions of Windows (I can only confirm for Win10) can simply pipe to
clip
. I'm using msysgit 1.9.5 and this worked. -
Admin over 8 years@mike,
xsel -ib
works for me.xsel
andxclip
are implemented differently,xclip
was what I was using but I'm working out of a chroot andxclip
stopped copying data to the clipboard a few weeks ago, I switched toxsel -ib
and haven't had any problems since. -
Charles Plager over 8 yearsThis works when you're on a single computer, but won't allow you to copy things between computers.
-
Miro over 8 yearsAt github page they suggest using
clip < ~/.ssh/id_rsa.pub
to copy SSH to clipboard. Reading this SO question I wonder how come is this possible? Isclip
a custom procedure that ships with git Bash? -
Michal aka Miki almost 8 yearsHow does this differ from
echo "foo" | xclip -selection c
? -
Colin D Bennett almost 8 yearsThere are some answers on this Ask Ubuntu answer, but mainly
xsel
andxclip
are equivalent in every way except thatxclip
can read/write files by name, butxsel
requires shell redirection if you want to access a file. -
Marcus Vinicius Pompeu over 7 yearsTo add a new alias: askubuntu.com/questions/17536/…
-
mh-cbon about 7 yearsany idea for wayland ?
-
Braden Best about 7 yearsDoesn't seem too surprising. Two different X servers = two different selection sets. However, you could set up a script that takes input/output via
xsel/xclip
. For example, one end listens to see if any of the selections changed, and then automatically pipes it (via the named FIFO) over to the other script, which is listening to one or more pipes, which inserts it into its own X selection. Copying text would thus automatically result in the same text appearing in the other X session's selection. And don't forget about$DISPLAY
. -
Braden Best about 7 yearsDefinitely always remember to use
DISPLAY=
when calling an X application from a non-X environment. X apps need theDISPLAY
environment variable to figure out which server (or is there just one server handling multiple sessions?) they're talking to. TryDISPLAY=:1 firefox
(or whatever your display ID may be; mine just happens to be:1
) from a TTY, for example. -
HankCa about 7 yearsFor me the choice in my environment was
:%y+
in VIM. -
Braden Best about 7 yearsI don't see how a lack of root privileges factors into this.
-
horta about 7 years@BradenBest Lack of root privileges means I couldn't install things.
-
Braden Best about 7 yearsBut what would you be installing? X? On a server? Unless you're hosting some weird X forwarding service, I can't see why you would ever want to do that.
-
horta about 7 years@BradenBest Not sure. Whatever program or service would allow me to perform a copy paste.
-
Braden Best about 7 yearsWell, if you're using any of the
X selections
(which is necessarily implied by "clipboard" and any mentions of xclip/xsel), you need an active X session (and thus an X server) so that you can access the selection in the first place. To see what I mean, try runningDISPLAY="" xsel
on your local machine. It will exit on an error, being unable to find session""
, and no interaction with any X selection will be made. That's why I initially said that I don't see how root privileges factor into this: root or no root, you're not likely to find an X selection useful in a server environment. -
jpaugh over 6 years@kr85
clip.exe
is a builtin windows program which git-bash has access to, but it only works one-way (copying, not pasting). If you're using git-bash, then you're also on Windows. -
jpaugh over 6 years@eduncan911 I cannot find mention of
.bash_aliases
in the bash manual. I believe that must be a distro-specific modification to.bashrc
. (I have seen distro-specific.bashrc
s which import.bash_profile
if it exists.) Based on that, I'd say.bash_aliases
is not a universal convention, but a convenient shorthand for those who have it. -
eduncan911 over 6 years@jpaugh you are correct. my
.bashrc
sources.bash_aliases
at the end. ;) I follow this old convention, that remains 100% compatible across Arch, Ubuntu/Debian, Raspberry variants, macOS/OSX and Windows Bash: stefaanlippens.net/my_bashrc_aliases_profile_and_other_stuff With that convention, I use the exact same dotfiles across all of the machines I touch. It's quite nice: github.com/eduncan911/dotfiles -
jpaugh over 6 years@eduncan911 Thanks! I'm working on my own dotfiles repo, so that's a great resource. A nice thing about having a separate file is, you can easily reload your
.bash_aliases
whenever it changes (via a$PROMPT_COMMAND
which compares timestamps). I have already done that the hard way, with an auto-reloading .bashrc. -
eduncan911 over 6 yearsI just have to stress: if you ever, ever think you'll use your dotfiles on any other operating system than you are writing them for (OSX, Ubuntu, BSD, Arch, Windows Bash, etc), take note of my bash files in that repo: see how I am always querying for resources FIRST, and if they exist, load them. I sometimes go looking in multiple locations (OS distros) to load the same resource. Doing this now, always checking if files exist, will save you a lot of grief and keep things compatible. Also note the dot organization in the link I posted earlier. Specifically how
.bash_profile
ties in. -
yurenchen over 6 yearsseems only ` echo str > tmpfile` and
cat tmpfile
, not clipboard operation. //same as @horta answers. -
MeadowMuffins over 6 yearsGreat, your alias part corresponds to MacOS quite well.
-
Gordon Bean almost 6 yearsIf you're using the Linux subsystem on Windows 10
cat file.txt | clip.exe
may work for copying to the system clipboard. See github.com/Microsoft/WSL/issues/1069 -
Todd Walton over 5 yearsbash does have a clipboard, though the documentation calls it a "kill ring". gnu.org/software/bash/manual/html_node/…
-
lhunath over 5 yearsFYI, that's
readline
, notbash
itself, but yes, it is accessible from bash, though only within the active process. -
Johnny over 5 yearsAre you sure that it's a safe
npm
package? -
Evan Conrad over 5 years@Stas, I would hope so, it's made by Sindresorhus (github.com/sindresorhus), the most prolific node contributor. He's responsible for the Ava testing library, the xo linter, Yeoman, and countless other projects. He's also responsible for countless small libraries like this, that collectively put his code on nearly every JS-using website on the internet. That's not to say he couldn't be compromised; just that the amount of eyes on his repos and his own reputation make it much less likely than most random npm repos.
-
hanshenrik over 5 years
clip
is bundled with windows since windows 7. also, since it's microsoft we're talking about, they obviously had to make a terrible program - with clip you can only write TO the clipboard, it can't help you read it. -
jena over 5 yearsHow would I use this? Save script into PATH and pipe into it? I'm trying to write dropbox cli wrapper to copy sharing links, so I just need it to handle text.
-
VonC over 5 years
-
jena over 5 yearsthis doesn't seem to set clipboard variable, so I cannot paste the content in other application - it's not a real clipboard!
-
user1529413 over 5 years
echo "foo" > /dev/clipboard
seems to destroy newlines completely (not a \r\n \n thing but completely gone) -
Yngvar Kristiansen almost 5 years
xclip
didn't work for me when putting it into a bash script (I'm on XFCE).xsel
works. In my bash script, I use:printf abc | xsel --input --clipboard
. Details: unix.stackexchange.com/questions/316715/… -
ledawg almost 5 yearsRunning Debian in the WSL environment in Windows 10 Pro and no cigar guys, had to manually copy and paste.
-
NVRM over 4 years
xsel
is working nicely from scripts, whilexclip
is working only from the prompt. Not sure why. -
Kevin Buchs over 4 yearsCool! Working on Ubuntu GNU/Linux where xclip is not working.
-
kintsukuroi about 4 yearsAdding
-r
to xclip will remove the newline in the end. Soecho 'test string 456' | xclip -r -selection c
-
kintsukuroi about 4 yearsAdding
-r
to xclip will remove the newline in the end. Soecho 'test string 456' | xclip -r -selection c
would work well in a single line. -
chovy almost 4 yearsdoesn't seem to work with gnome from hyper terminal
-
peter karasev over 3 years"-r" argument does not seem to work on current ubuntu. To remove new line you may try this:
uptime | tr -d '\n' | xclip -selection c
-
crimson_king over 3 years@mh-cbon I believe xclip works on Wayland sessions too. I have been using
pass
(the CLI password manager) for a long time on Fedora Workstation, and it usesxclip
to copy a password to the clipboard. -
mh-cbon over 3 years@crimson_king on wayland i now use wl-clipboard. It works like a charm github.com/bugaevc/wl-clipboard
-
Timo over 3 yearsQuestion answered over 10 years ago, updated just now. Great, welcome to SO.
-
izzulmakin over 3 yearson Mac OSX's bash use
pbcopy
andpbpaste
-
sytech over 3 yearsYou can just drop the brackets and use a generator expression instead of a list comprehension.
''.join(f' {l}' for l in sys.stdin)
-- also for most folkspython
will point to python2 on MacOS. So, you may want to specifypython3
instead. -
Kipras Melnikovas over 3 yearsbroken link fix (couldn't edit): pgrs.net/2008/01/11/command-line-clipboard-access
-
Kangqiao Zhao over 3 yearsWhile it is not work in WSL -- a linux in windows.
-
TNT about 3 yearsAlso available on Redhat based systems. Doesn't strangely block when used in scripts like xclip does.
-
vatosarmat almost 3 yearsThere is too much JS around
-
Wellington1993 almost 3 yearsWorks with Yarn too:
yarn global add clipboard-cli
-
csaba.sulyok over 2 yearsCan't use it on a server through SSH because it needs a working UI (github.com/sindresorhus/clipboardy/issues/63). Useless without it as far as I'm concerned.
-
Peter Mortensen over 2 yearsBut already covered by previous answers(?).
-
Peter Mortensen over 2 yearsWhat is "the Ruby oneliner"? What are you referring to? Another answer? Or something else? Please respond by editing (changing) your answer, not here in comments (without "Edit:", "Update:", or similar - the answer should appear as if it was written today).
-
Anthony Miller over 2 yearsThis works in gitbash as well.