Pipe to/from the clipboard in Bash script

2019-01-03 19:19发布

问题:

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

回答1:

You're a little ambiguous. I expect you're probably a Linux user inside X who wants to put stuff in the X PRIMARY clipboard.

It's important to understand that bash doesn't have a clipboard. There is no such thing as "the" clipboard, because bash can run on Windows, Mac OS X, lots of other OSes, inside X, outside X, ... Not to mention that X itself has three different clipboards. There's a wealth of clipboards you could be dealing with. Usually the clipboard you want to talk to has a utility that lets you talk to it.

In case of X, yes, 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 trying to talk to the Mac OS X clipboard, there's pbcopy.

If you're in Linux terminal mode (no X) then maybe you need to look into gpm.

There's also GNU screen which has a clipboard. To put stuff in there, look at the screen command "readreg".

Under Windows/cygwin, use /dev/clipboard or clip for newer versions of Windows (at least Windows 10).



回答2:

Make sure you are using alias xclip="xclip -selection c" otherwise you can't just use to Ctrl+v to paste it back in a different place.

echo test | xclip    

Ctrl+v === test



回答3:

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


回答4:

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.



回答5:

Try

xclip

xclip - command line interface to X selections (clipboard) 

man



回答6:

xsel on Debian/Ubuntu/Mint

# append to clipboard:
cat 'the file with content' | xsel -ib

# or type in the happy face :) and ...
echo 'the happy face :) and content' | xsel -ib

# show clipboard
xsel -b

# Get more info:
man xsel

Install

sudo apt-get install xsel


回答7:

Here is a ready to use bash script for reading the clipboard which works on multiple platforms. Please edit the script here if you add functionality (e.g. more platforms).

#!/bin/bash
# WF 2013-10-04
# multi platform clipboard read access
# supports
#   Mac OS X
#   git shell / Cygwin (Windows)
#   Linux (e.g. Ubuntu)

#
# display an error
#
error() {
  echo "error: $1" 1>&2
  exit 1
}

#
# getClipboard
#
function getClipboard() {
 os=`uname`
      case $os in 
        # git bash  (Windows)
        MINGW32_NT-6.1)
          cat /dev/clipboard;;
        # Mac OS X
        Darwin*)
          pbpaste;;  
        # Linux 
        Linux*)
          # works only for X clipboard - a check that X is running might be due
          xclip -o;;
        *)
          error "unsupported os $os";;
      esac
}

tmp=/tmp/clipboard$$
getClipboard >$tmp
cat $tmp
# comment out for debugging
rm $tmp


回答8:

Wow, I can't believe how many answers there are for this question. I can't say I've tried them all but I've tried the top 3 or 4 and none of them work for me. What did work for me was an answer located in one of the comment written by a user called doug. Since I found it so helpful, I decided to restate in an answer.

Install xcopy utility and when you're in the Terminal, input:

Copy

Thing_you_want_to_copy|xclip -selection c

Paste

myvariable=$(xclip -selection clipboard -o)

I noticed alot of answers recommended pbpaste and pbcopy. If you're into those utilities but for some reason they are not available on your repo, you can always make an alias for the xcopy commands and call them pbpaste and pbcopy.

alias pbcopy="xclip -selection c" 
alias pbpaste="xclip -selection clipboard -o" 

So then it would look like this:

Thing_you_want_to_copy|pbcopy
myvariable=$(pbpaste)


回答9:

On Windows (with Cygwin) try cat /dev/clipboard or echo "foo" > /dev/clipboard as mentioned in this article.



回答10:

For Mac only:

echo "Hello World" | pbcopy
pbpaste

These are located /usr/bin/pbcopy and /usr/bin/pbpaste.



回答11:

There are different clipboards in Linux; the X server has one, the window manager might have another one, etc. There is no standard device.

Oh, yes, on CLI, the screen program has its own clipboard as well, as do some other applications like Emacs and vi.

In X, you can use xclip.

You can check this thread for other possible answers: http://unix.derkeiler.com/Newsgroups/comp.unix.shell/2004-07/0919.html



回答12:

On the Windows subsystem for Linux you can copy to the clipboard with clip.exe.

cat file | clip.exe

Keep in mind to use the | pipe command. And not a > command, since that will not work.



回答13:

Copy and paste to clipboard in Windows (Cygwin):

see:

$ clip.exe -?

CLIP Description: Redirects output of command line tools to the Windows clipboard. This text output can then be pasted into other programs. Parameter List: /? Displays this help message. Examples: DIR | CLIP Places a copy of the current directory listing into the Windows clipboard. CLIP < README.TXT Places a copy of the text from readme.txt on to the Windows clipboard.

Also exists getclip (can be used instead of shift+ins!), putclip (echo oaeuoa | putclip.exe to put it into clip)



回答14:

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



回答15:

  xsel -b

Does the job for x11, it is mostly already installed. A look in the man page of xsel is worth the effort.



回答16:

This is a simple Python script that does just what you need:

#!/usr/bin/python

import sys

# Clipboard storage
clipboard_file = '/tmp/clipboard.tmp'

if(sys.stdin.isatty()): # Should write clipboard contents out to stdout
    with open(clipboard_file, 'r') as c:
        sys.stdout.write(c.read())
elif(sys.stdout.isatty()): # Should save stdin to clipboard
    with open(clipboard_file, 'w') as c:
        c.write(sys.stdin.read())

Save this as an executable somewhere in your path (I saved it to /usr/local/bin/clip. You can pipe in stuff to be saved to your clipboard...

echo "Hello World" | clip

And you can pipe what's in your clipboard to some other program...

clip | cowsay
 _____________
< Hello World >
 -------------
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||

Running it by itself will simply output what's in the clipboard.



回答17:

A few Windows programs I wrote years ago. They allow you dump, push, append and print the clipboard. It works like this:

dumpclip | perl -pe "s/monkey/chimp/g;" | pushclip

It includes source code: cmd_clip.zip



回答18:

There are a couple ways. Some of the ways that have been mentioned include (I think) tmux, screen, vim, emacs, and the shell. I don't know emacs or screen, so I'll go over the other three.

Tmux

While not an X selection, tmux has a copy mode accessible via prefix-[ (prefix is Ctrl+B by default). The buffer used for this mode is separate and exclusive to tmux, which opens up quite a few possibilities and makes it more versatile than the X selections in the right situations.

To exit this mode, hit q; to navigate, use your vim or emacs binding (default = vim), so hjkl for movement, v/V/C-v for character/line/block selection, etc. When you have your selection, hit Enter to copy and exit the mode.

To paste from this buffer, use prefix-].

Shell

Any installation of X11 seems to come with two programs by default: xclip and xsel (kinda like how it also comes with both startx and xinit). Most of the other answers mention xclip, and I really like xsel for its brevity, so I'm going to cover xsel.

From xsel(1x):

Input options

-a, --append

append standard input to the selection. Implies -i.

-f, --follow

append to selection as standard input grows. Implies -i.

-i, --input

read standard input into the selection.

Output options

-o, --output

write the selection to standard output.

Action options

-c, --clear

clear the selection. Overrides all input options.

-d, --delete

Request that the current selection be deleted. This not only clears the selection, but also requests to the program in which the selection resides that the selected contents be deleted. Overrides all input options.

Selection options

-p, --primary

operate on the PRIMARY selection (default).

-s, --secondary

operate on the SECONDARY selection.

-b, --clipboard

operate on the CLIPBOARD selection.

And that's about all you need to know. p (or nothing) for PRIMARY, s for SECONDARY, b for CLIPBOARD, o for output.

Example: say I want to copy the output of foo from a TTY and paste it to a webpage for a bug report. To do this, it would be ideal to copy to/from the TTY/X session. So the question becomes how do I access the clipboard from the TTY?

For this example, we'll assume the X session is on display :1.

$ foo -v
Error: not a real TTY
details:
blah blah @ 0x0000000040abeaf4
blah blah @ 0x0000000040abeaf8
blah blah @ 0x0000000040abeafc
blah blah @ 0x0000000040abeb00
...
$ foo -v | DISPLAY=:1 xsel -b # copies it into clipboard of display :1

Then I can Ctrl-V it into the form as per usual.

Now say that someone on the support site gives me a command to run to fix the problem. It's complicated and long.

$ DISPLAY=:1 xsel -bo
sudo foo --update --clear-cache --source-list="http://foo-software.com/repository/foo/debian/ubuntu/xenial/164914519191464/sources.txt"
$ $(DISPLAY=:1 xsel -bo)
Password for braden:
UPDATING %%%%%%%%%%%%%%%%%%%%%%% 100.00%
Clearing cache...
Fetching sources...
Reticulating splines...
Watering trees...
Climbing mountains...
Looking advanced...
Done.
$ foo
Thank you for your order. A pizza should arrive at your house in the next 20 minutes. Your total is $6.99

Pizza ordering seems like a productive use of the command line.

...moving on.

Vim

If compiled with +clipboard (This is important! Check your vim --version), Vim should have access to the X PRIMARY and CLIPBOARD selections. The two selections are accessible from the * and + registers, respectively, and may be written to and read from at your leisure the same as any other register. For example:

:%y+    ; copy/yank (y) everything (%) into the CLIPBOARD selection (+)
"+p     ; select (") the CLIPBOARD selection (+) and paste/put it
ggVG"+y ; Alternative version of the first example

If your copy of vim doesn't directly support access to X selections, though, it's not the end of the world. You can just use the xsel technique as described in the last section.

:r ! xsel -bo ; read  (r) from the stdout of (!) `xsel -bo`
:w ! xsel -b  ; write (w) to the stdin of    (!) `xsel -b`

Bind a couple key combos and you should be good.



回答19:

From this thread, there is an option which does not require installing any gclip/xclip/xsel third-party software.

A perl script (since perl is usually always installed)

use Win32::Clipboard;
print Win32::Clipboard::GetText();


回答20:

If you're like me and run on a linux server without root privileges and there's no xclip or gpm you could workaround this issue by just using a temporary file. For example:

$ echo "hello world" > ~/clip
$ echo `cat ~/clip`
hello world


回答21:

in macOS use pbpaste

eg:

update the clipboard

pbpaste | ruby -ne ' puts "\|" + $_.split( )[1..4].join("\|") ' | pbcopy

enjoy.



回答22:

There is also xclip-copyfile.



回答23:

Although >1 year later, I share a slightly different solution. Hope this is useful for somebody.

Yesterday I found myself with the question: "How to share the clipboard between different user sessions?". When switching between sessions with ctrlaltF7 - ctrlaltF8, in fact, you can't paste what you copied.

I came up with the following quick & dirty solution, based on a named pipe. It is surely quite bare and raw, but I found it functional:

user1@host:~$ mkfifo /tmp/sharedClip

then in the sending terminal

user1@host:~$ cat > /tmp/sharedClip

last, in the receiving terminal:

user2@host:~$ cat /tmp/sharedClip

Now, you type or paste anything in the first terminal, and (after hitting return), it will appear immediately in the receiving terminal, from where you can Copy/Paste again anywhere you like.

Of course this doesn't just strictly take the content from user1's clipboard to make it available in user2's clipboard, but rather it requires an additional pair of Paste & Copy clicks.



标签: