Pipe to/from the clipboard in a Bash script

690,676

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
Share:
690,676
moinudin
Author by

moinudin

Islamic revert studying the din full time in UK

Updated on April 25, 2022

Comments

  • moinudin
    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
      Braden Best over 8 years
      I've been using :%y+ in vim, which is vim-speak for "yank (copy) all the lines into the '+' register (the X PRIMARY 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 the xclip 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
      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
      Braden Best about 7 years
      @HankCa Okay, I posted an answer. Tell me what you think.
    • HankCa
      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
      VonC over 6 years
      Another option: using a little perl script: no installation require. See my answer below.
    • ctrl-alt-delor
      ctrl-alt-delor over 4 years
      You 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
      Antonio Costa over 3 years
      My simple solution to copy, for example, ls output is : ls | xclip -i -selection clipboard.
  • moinudin
    moinudin about 15 years
    I am perfectly aware of the multiple clipboards. How does this make my question any more difficult to answer?
  • glenn jackman
    glenn jackman almost 13 years
    cygwin: /dev/clipboard
  • Mihai Rotaru
    Mihai Rotaru almost 13 years
    on Windows, /dev/clipboard also works for Msys/MinGW bash shells
  • Klaas van Schelven
    Klaas van Schelven almost 13 years
    Note that xclip -selection c will send data to the clipboard that works with ^C, ^V in most applications
  • maep
    maep over 12 years
    on newer windows versions you can just use clip like this: dir | clip
  • Jonah
    Jonah over 10 years
    How would one go about pasting it without that command argument?
  • doug
    doug over 10 years
    xclip -selection clipboard -o
  • doug
    doug over 10 years
    since 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
    ApockofFork about 10 years
    When 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
    David X about 10 years
    @ApockofFork, xclip isnt adding a newline, echo is. Try printf test | xclip -i -selection clipboard. (printf doesnt add a newline unless you write 'test\n'.)
  • Hi-Angel
    Hi-Angel over 9 years
    It 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
    mike over 9 years
    Under X11, there is also xsel which operates on the X selection by default. So you can echo hello | xsel or xsel|wc and so on without using a commmand-line switch.
  • Christian Pietsch
    Christian Pietsch over 9 years
    Or use echo -n instead of printf.
  • Admin
    Admin about 9 years
    It 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
    Scz almost 9 years
    For all other distros: you can download the source from sourceforge.net/projects/xclip
  • FractalSpace
    FractalSpace almost 9 years
    Also, on Windows: clip < <filename> or echo yes | clip
  • eduncan911
    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
    tleb over 8 years
    Thanks @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
    Shawn Erquhart over 8 years
    As 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
    Admin over 8 years
    @mike, xsel -ib works for me. xsel and xclip are implemented differently, xclip was what I was using but I'm working out of a chroot and xclip stopped copying data to the clipboard a few weeks ago, I switched to xsel -ib and haven't had any problems since.
  • Charles Plager
    Charles Plager over 8 years
    This works when you're on a single computer, but won't allow you to copy things between computers.
  • Miro
    Miro over 8 years
    At 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? Is clip a custom procedure that ships with git Bash?
  • Michal aka Miki
    Michal aka Miki almost 8 years
    How does this differ from echo "foo" | xclip -selection c?
  • Colin D Bennett
    Colin D Bennett almost 8 years
    There are some answers on this Ask Ubuntu answer, but mainly xsel and xclip are equivalent in every way except that xclip can read/write files by name, but xsel requires shell redirection if you want to access a file.
  • Marcus Vinicius Pompeu
    Marcus Vinicius Pompeu over 7 years
    To add a new alias: askubuntu.com/questions/17536/…
  • mh-cbon
    mh-cbon about 7 years
    any idea for wayland ?
  • Braden Best
    Braden Best about 7 years
    Doesn'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
    Braden Best about 7 years
    Definitely always remember to use DISPLAY= when calling an X application from a non-X environment. X apps need the DISPLAY environment variable to figure out which server (or is there just one server handling multiple sessions?) they're talking to. Try DISPLAY=:1 firefox (or whatever your display ID may be; mine just happens to be :1) from a TTY, for example.
  • HankCa
    HankCa about 7 years
    For me the choice in my environment was :%y+ in VIM.
  • Braden Best
    Braden Best about 7 years
    I don't see how a lack of root privileges factors into this.
  • horta
    horta about 7 years
    @BradenBest Lack of root privileges means I couldn't install things.
  • Braden Best
    Braden Best about 7 years
    But 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
    horta about 7 years
    @BradenBest Not sure. Whatever program or service would allow me to perform a copy paste.
  • Braden Best
    Braden Best about 7 years
    Well, 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 running DISPLAY="" 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
    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
    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 .bashrcs 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
    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
    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
    eduncan911 over 6 years
    I 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
    yurenchen over 6 years
    seems only ` echo str > tmpfile` and cat tmpfile , not clipboard operation. //same as @horta answers.
  • MeadowMuffins
    MeadowMuffins over 6 years
    Great, your alias part corresponds to MacOS quite well.
  • Gordon Bean
    Gordon Bean almost 6 years
    If 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
    Todd Walton over 5 years
    bash does have a clipboard, though the documentation calls it a "kill ring". gnu.org/software/bash/manual/html_node/…
  • lhunath
    lhunath over 5 years
    FYI, that's readline, not bash itself, but yes, it is accessible from bash, though only within the active process.
  • Johnny
    Johnny over 5 years
    Are you sure that it's a safe npm package?
  • Evan Conrad
    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
    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
    jena over 5 years
    How 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
    VonC over 5 years
  • jena
    jena over 5 years
    this doesn't seem to set clipboard variable, so I cannot paste the content in other application - it's not a real clipboard!
  • user1529413
    user1529413 over 5 years
    echo "foo" > /dev/clipboard seems to destroy newlines completely (not a \r\n \n thing but completely gone)
  • Yngvar Kristiansen
    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
    ledawg almost 5 years
    Running Debian in the WSL environment in Windows 10 Pro and no cigar guys, had to manually copy and paste.
  • NVRM
    NVRM over 4 years
    xsel is working nicely from scripts, while xclip is working only from the prompt. Not sure why.
  • Kevin Buchs
    Kevin Buchs over 4 years
    Cool! Working on Ubuntu GNU/Linux where xclip is not working.
  • kintsukuroi
    kintsukuroi about 4 years
    Adding -r to xclip will remove the newline in the end. So echo 'test string 456' | xclip -r -selection c
  • kintsukuroi
    kintsukuroi about 4 years
    Adding -r to xclip will remove the newline in the end. So echo 'test string 456' | xclip -r -selection c would work well in a single line.
  • chovy
    chovy almost 4 years
    doesn't seem to work with gnome from hyper terminal
  • peter karasev
    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
    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 uses xclip to copy a password to the clipboard.
  • mh-cbon
    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
    Timo over 3 years
    Question answered over 10 years ago, updated just now. Great, welcome to SO.
  • izzulmakin
    izzulmakin over 3 years
    on Mac OSX's bash use pbcopy and pbpaste
  • sytech
    sytech over 3 years
    You 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 folks python will point to python2 on MacOS. So, you may want to specify python3 instead.
  • Kipras Melnikovas
    Kipras Melnikovas over 3 years
    broken link fix (couldn't edit): pgrs.net/2008/01/11/command-line-clipboard-access
  • Kangqiao Zhao
    Kangqiao Zhao over 3 years
    While it is not work in WSL -- a linux in windows.
  • TNT
    TNT about 3 years
    Also available on Redhat based systems. Doesn't strangely block when used in scripts like xclip does.
  • vatosarmat
    vatosarmat almost 3 years
    There is too much JS around
  • Wellington1993
    Wellington1993 almost 3 years
    Works with Yarn too: yarn global add clipboard-cli
  • csaba.sulyok
    csaba.sulyok over 2 years
    Can'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
    Peter Mortensen over 2 years
    But already covered by previous answers(?).
  • Peter Mortensen
    Peter Mortensen over 2 years
    What 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
    Anthony Miller over 2 years
    This works in gitbash as well.