1278

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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
moinudin
  • 134,091
  • 45
  • 190
  • 216
  • 6
    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. – Braden Best Oct 22 '15 at 04:41
  • 1
    @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. – HankCa May 11 '17 at 01:15
  • @HankCa Okay, I posted [an answer](http://stackoverflow.com/a/43906295/1175714). Tell me what you think. – Braden Best May 11 '17 at 04:01
  • @BradenBest its a very comprehensive answer. I just liked the `:%y+` one but ok, you've got all bases covered! Good one. – HankCa May 15 '17 at 06:53
  • Another option: using a little perl script: no installation require. See [my answer below](https://stackoverflow.com/a/46374833/6309). – VonC Sep 23 '17 at 00:25
  • 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? – ctrl-alt-delor Aug 24 '19 at 17:48
  • My simple solution to *copy*, for example, `ls` output is : `ls | xclip -i -selection clipboard`. –  Dec 04 '20 at 12:35

32 Answers32

1106

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
lhunath
  • 120,288
  • 16
  • 68
  • 77
  • 41
    cygwin: [/dev/clipboard](http://williammitchell.blogspot.com/2008/03/fun-with-cygwins-devclipboard.html) – glenn jackman May 31 '11 at 13:48
  • 29
    on Windows, `/dev/clipboard` also works for Msys/MinGW bash shells – Mihai Rotaru Jun 07 '11 at 12:43
  • 79
    Note that `xclip -selection c` will send data to the clipboard that works with ^C, ^V in most applications – Klaas van Schelven Aug 14 '11 at 15:23
  • 35
    on newer windows versions you can just use `clip` like this: `dir | clip` – maep Nov 08 '11 at 12:43
  • 11
    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)*. – Hi-Angel Sep 04 '14 at 10:18
  • 2
    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. – mike Sep 29 '14 at 03:10
  • Also, on Windows: `clip < ` or `echo yes | clip` – FractalSpace Jul 10 '15 at 21:57
  • @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. –  Jan 01 '16 at 18:52
  • 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? – Miro Jan 06 '16 at 23:16
  • 1
    any idea for wayland ? –  Mar 16 '17 at 16:20
  • 1
    @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 Sep 05 '17 at 19:57
  • 1
    If you're using the Linux subsystem on Windows 10 `cat file.txt | clip.exe` may work for copying to the system clipboard. See https://github.com/Microsoft/WSL/issues/1069 – Gordon Bean Jul 18 '18 at 23:05
  • bash *does* have a clipboard, though the documentation calls it a "kill ring". https://www.gnu.org/software/bash/manual/html_node/Readline-Killing-Commands.html – Todd Walton Oct 03 '18 at 18:22
  • FYI, that's `readline`, not `bash` itself, but yes, it is accessible from bash, though only within the active process. – lhunath Oct 04 '18 at 19:39
  • `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. – hanshenrik Oct 25 '18 at 08:00
  • `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: https://unix.stackexchange.com/questions/316715/xclip-works-differently-in-interactive-and-non-interactive-shells – Yngvar Kristiansen May 24 '19 at 09:00
  • Running Debian in the WSL environment in Windows 10 Pro and no cigar guys, had to manually copy and paste. – ledawg Aug 17 '19 at 11:02
  • 1
    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. – kintsukuroi Mar 11 '20 at 07:11
  • doesn't seem to work with gnome from hyper terminal – chovy Jun 01 '20 at 23:08
  • @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. – crimson_king Oct 14 '20 at 00:28
  • 1
    @crimson_king on wayland i now use wl-clipboard. It works like a charm https://github.com/bugaevc/wl-clipboard –  Oct 14 '20 at 06:04
  • 1
    Question answered over 10 years ago, updated just now. Great, welcome to SO. – Timo Nov 06 '20 at 08:17
  • on Mac OSX's bash use `pbcopy` and `pbpaste` – izzulmakin Dec 29 '20 at 03:00
361

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

recvfrom
  • 389
  • 6
  • 14
doug
  • 4,010
  • 1
  • 15
  • 10
  • 1
    How would one go about pasting it _without_ that command argument? – Jonah Dec 17 '13 at 18:25
  • 20
    `xclip -selection clipboard -o` – doug Dec 18 '13 at 19:14
  • 43
    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. – doug Dec 18 '13 at 19:14
  • 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? – ApockofFork Mar 19 '14 at 13:36
  • 17
    @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'`.) – David X Apr 27 '14 at 20:53
  • 10
    Or use `echo -n` instead of `printf`. – Christian Pietsch Feb 13 '15 at 12:00
  • To add a new alias: http://askubuntu.com/questions/17536/how-do-i-create-a-permanent-bash-alias – Marcus Vinicius Pompeu Oct 15 '16 at 00:28
  • Adding `-r` to xclip will remove the newline in the end. So `echo 'test string 456' | xclip -r -selection c` – kintsukuroi Mar 11 '20 at 07:08
  • "-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` – peter karasev Sep 27 '20 at 22:17
244

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
tleb
  • 4,395
  • 3
  • 25
  • 33
  • 3
    For all other distros: you can download the source from http://sourceforge.net/projects/xclip/ – Scz Jul 06 '15 at 11:43
  • +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. – eduncan911 Sep 17 '15 at 07:50
  • 1
    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. :) – tleb Sep 19 '15 at 16:13
  • @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. – jpaugh Sep 05 '17 at 20:00
  • 1
    @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: http://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: https://github.com/eduncan911/dotfiles – eduncan911 Sep 05 '17 at 22:46
  • @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](https://gist.github.com/jpaugh/11d06ee4b02acff784bfc61964a0263a#file-bashrc-L15). – jpaugh Sep 06 '17 at 13:54
  • 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. – eduncan911 Sep 06 '17 at 17:27
186

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
Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
jtruelove
  • 3,306
  • 3
  • 25
  • 29
  • `pbcopy < my_clipboard.txt` can also be used for copying contents from a file. – Praveen Jul 14 '22 at 21:06
  • Nice! I usually do `cat my_clipboard.txt | pbcopy` to copy the contents of a file to my clipboard, but `pbcopy < my_clipboard.txt` is way smoother. – leifericf Jun 07 '23 at 08:10
67

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
Evan Conrad
  • 3,993
  • 4
  • 28
  • 46
  • 12
    Are you sure that it's a safe `npm` package? – Johnny Oct 21 '18 at 10:10
  • 13
    @Stas, I would hope so, it's made by Sindresorhus (https://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. – Evan Conrad Oct 22 '18 at 15:53
  • Cool! Working on Ubuntu GNU/Linux where xclip is not working. – Kevin Buchs Feb 13 '20 at 22:38
  • While it is not work in WSL -- a linux in windows. – Kangqiao Zhao Feb 06 '21 at 08:01
  • 9
    There is too much JS around – vatosarmat May 28 '21 at 06:14
  • Works with Yarn too: `yarn global add clipboard-cli` – Wellington1993 Jul 22 '21 at 19:11
  • Can't use it on a server through SSH because it needs a working UI (https://github.com/sindresorhus/clipboardy/issues/63). Useless without it as far as I'm concerned. – csaba.sulyok Aug 27 '21 at 08:58
53

xsel on Debian/Ubuntu/Mint

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

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

# show clipboard
xsel -ob

# Get more info:
man xsel

Install

sudo apt-get install xsel
SebMa
  • 4,037
  • 29
  • 39
Andrew_1510
  • 12,258
  • 9
  • 51
  • 52
  • How does this differ from `echo "foo" | xclip -selection c`? – Léo Léopold Hertz 준영 Jun 16 '16 at 09:49
  • There are some answers on this [Ask Ubuntu answer](http://askubuntu.com/questions/705620/xclip-vs-xsel), 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. – Colin D Bennett Aug 09 '16 at 16:44
  • 3
    `xsel` is working nicely from scripts, while `xclip` is working only from the prompt. Not sure why. – NVRM Oct 19 '19 at 03:28
  • Also available on Redhat based systems. Doesn't strangely block when used in scripts like xclip does. – TNT Apr 01 '21 at 18:33
43

Try

xclip

xclip - command line interface to X selections (clipboard) 

man

Zombo
  • 1
  • 62
  • 391
  • 407
Zoredache
  • 37,543
  • 7
  • 45
  • 61
38

On the Windows Subsystem for Linux (WSL) 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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
knowledge_is_power
  • 868
  • 1
  • 11
  • 10
22

Install the 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 a lot of answers recommended pbpaste and pbcopy. If you're into those utilities, but for some reason they are not available in your repository, 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)

An answer located in one of the comments written by a user called doug work for me. Since I found it so helpful, I decided to restate in an answer.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
thebunnyrules
  • 1,520
  • 15
  • 22
14

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 the 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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Wolfgang Fahl
  • 15,016
  • 11
  • 93
  • 186
12

For Mac only:

echo "Hello World" | pbcopy
pbpaste

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

kenorb
  • 155,785
  • 88
  • 678
  • 743
nyitguy
  • 598
  • 4
  • 18
11

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

Norman H
  • 2,248
  • 24
  • 27
  • 2
    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. – Shawn Erquhart Dec 17 '15 at 15:01
  • 1
    `echo "foo" > /dev/clipboard` seems to destroy newlines completely (not a \r\n \n thing but completely gone) – user1529413 Feb 11 '19 at 13:07
  • 1
    broken link fix (couldn't edit): https://www.pgrs.net/2008/01/11/command-line-clipboard-access/ – Kipras Melnikovas Jan 25 '21 at 22:08
  • Yeah @user1529413, seems to be a bit flaky too. `printf " Hi \r\n there" > /dev/clipboard; sed 's/^\(.*\)/CLIP: "\1"/' /dev/clipboard` sometimes shows `CLIP: " HI "`, and sometimes doesn't show anything at all. It's like it goes to sleep. :D – Adrian Nov 26 '22 at 01:39
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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sunny Milenov
  • 21,990
  • 6
  • 80
  • 106
  • 2
    I am perfectly aware of the multiple clipboards. How does this make my question any more difficult to answer? – moinudin Apr 14 '09 at 22:23
  • It would make sense if clipboards were standardized, probably wouldn't hurt if you could use /dev/clip1, /dev/clip2 .. /dev/clip 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. –  Mar 14 '15 at 15:00
7

I have found a good reference: How to target multiple selections with xclip

In my case, I would like to paste content on the clipboard and also to see what is been pasted there, so I used also the tee command with a file descriptor:

echo "just a test" | tee >(xclip -i -selection clipboard)

>() is a form of process substitution. Bash replaces each with the path to a file descriptor which is connected to the standard input of the program within the parentheses.

The teecommand forks your command allowing you to "pipe its content" and see the result on standard output "stdout".

You can also create aliases to get and write on the clipboard, allowing you to use "pbcopy" and "pbpaste" as if you where on Mac. In my case, as I use Z shell (zsh), I have this in my aliases file:

(( $+commands[xclip] )) && {
    alias pbpaste='xclip -i -selection clipboard -o'
    alias pbcopy='xclip -selection clipboard'
}

The (( $+command[name] )) in Z shell tests if the command "name" is installed on your system, and then both aliases are grouped with {}. The && is a binary AND; if a then b, hence if you have xclip then the aliases will be set.

echo "another test" | tee >(pbcopy)

To get your clipboard content, just type:

pbpaste | "any-command-you-need-here"
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
SergioAraujo
  • 11,069
  • 3
  • 50
  • 40
7

I just searched the same stuff in my KDE environment.

Feel free to use clipcopy and clippaste.

KDE:

> echo "TEST CLIP FROM TERMINAL" | clipcopy
> clippaste
TEST CLIP FROM TERMINAL
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
whati001
  • 317
  • 2
  • 9
6

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
tysweat
  • 79
  • 1
  • 3
  • This works when you're on a single computer, but won't allow you to copy things between computers. – Charles Plager Jan 06 '16 at 19:51
  • seems only ` echo str > tmpfile` and `cat tmpfile` , not clipboard operation. //same as @horta answers. – yurenchen Sep 26 '17 at 18:08
  • this doesn't seem to set clipboard variable, so I cannot paste the content in other application - it's not a real clipboard! – jena Nov 27 '18 at 22:20
  • Didn't work on `git bash` terminal with windows `python` 3.10.7 running. Too bad. I tried `printf " Hi \r\n there" | pclip; pclip | sed 's/^\(.*\)$/CLIP: "\1"/'` and nothing came out. – Adrian Nov 26 '22 at 01:50
6

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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jens Timmerman
  • 9,316
  • 1
  • 42
  • 48
5

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 getclip (it can be used instead of Shift + Ins!) and putclip (echo oaeuoa | putclip.exe to put it into clip) exist.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Stenemo
  • 611
  • 7
  • 13
5
  xsel -b

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
5

In Linux this works:

cat filename | xclip
otto
  • 1,815
  • 7
  • 37
  • 63
  • 1
    But already covered by previous answers(?). – Peter Mortensen Aug 28 '21 at 22:54
  • 1
    @PeterMortensen yes and no. When reading https://stackoverflow.com/a/4208191/11154841 and https://stackoverflow.com/a/27456981/11154841, you think that you need to make an alias like `alias xclip="xclip -selection c"`. But xclip does not seem to need to have this alias, see also [How to pipe text from command line to the clipboard - Super User](https://superuser.com/a/124282/1192848) in 2010. – questionto42 Dec 30 '22 at 10:26
5

pbcopy is built into OS X:

Copying the content of file .bash_profile:

cat ~/.bash_profile | pbcopy
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Skulas
  • 457
  • 6
  • 6
4

There are a couple of 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 (kind of 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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Braden Best
  • 8,830
  • 3
  • 31
  • 43
  • 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. – Braden Best May 11 '17 at 04:27
  • For me the choice in my environment was `:%y+` in VIM. – HankCa May 15 '17 at 06:54
2

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
jeng
  • 21
  • 1
  • 3
2

Yesterday I found myself with the question: "How can I share the clipboard between different user sessions?". When switching between sessions with Ctrl + Alt + F7 - Ctrl + Alt + F8, 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 and 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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
lurix66
  • 502
  • 1
  • 5
  • 14
  • 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 May 11 '17 at 04:13
2

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();
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • 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. – jena Nov 27 '18 at 20:53
  • @jena Example: https://metacpan.org/pod/Win32::Clipboard or https://www.perlmonks.org/?node_id=143637 or http://www.bribes.org/perl/docfr/win32clipboard.html. – VonC Nov 27 '18 at 21:37
  • Doesn't work with `git bash` (`cpan` is broken and won't download anything) or `MSYS2` (`cpan` did attempt it, but said that the OS isn't supported). – Adrian Nov 26 '22 at 01:27
  • @Adrian True. For Windows (even from a Git bash session), I would call an executable (compiled in Go) which uses [win32 DLL calls to read Windows clipboard](https://github.com/atotto/clipboard/blob/1438b322bde482cc6decd8bc53dbe2eece57668b/clipboard_windows.go#L22-L28). That way, I can [copy/paste](https://github.com/atotto/clipboard#commands). – VonC Nov 26 '22 at 05:52
2

The Ruby oneliner inspired me to try with Python.

Say we want a command that indents whatever is in the clipboard with four spaces. It is perfect for sharing snippets on Stack Overflow.

$ pbpaste | python -c "import sys
 for line in sys.stdin:
   print(f'    {line}')" | pbcopy

That's not a typo. Python needs newlines to do a for loop. We want to alter the lines in one pass to avoid building up an extra array in memory.

If you don't mind building the extra array try:

$ pbpaste | python -c "import sys; print(''.join([f'    {l}' for l in sys.stdin]))" | pbcopy

but honestly awk is better for this than python. I defined this alias in my ~/.bashrc file

alias indent="pbpaste | awk '{print \"    \"\$0}' | pbcopy"

Now when I run indent, whatever is in my clipboard is indented.

Harry Moreno
  • 10,231
  • 7
  • 64
  • 116
  • 1
    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. – sytech Jan 20 '21 at 06:26
  • What is "the Ruby oneliner"? What are you referring to? Another answer? Or something else? Please respond by [editing (changing) your answer](https://stackoverflow.com/posts/61265818/edit), not here in comments (***without*** "Edit:", "Update:", or similar - the answer should appear as if it was written today). – Peter Mortensen Aug 28 '21 at 23:00
1

In macOS, use pbpaste.

For example:

Update the clipboard

pbpaste  | ruby -ne ' puts "\|" + $_.split( )[1..4].join("\|") ' | pbcopy
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
jiahut
  • 1,451
  • 15
  • 14
1

A way to paste from the clipboard to a file without any tools except echo.

  1. Escape single quotes in the text you want to paste: replace all occurrences of ' with '\'' and copy the result to clipboard.
  2. Type echo -n '
  3. Press Shift + Insert
  4. Type ' > filename.txt
  5. Press Enter

Basically you're doing this:

echo -n 'copied "text" with '\''single quotes'\'' escaped' > filename.txt

It works even if the copied text has new lines.

Ilyich
  • 4,966
  • 3
  • 39
  • 27
1

For mac you can use this function which uses pbcopy and pbpaste, but a little easier:

Add this to your .bashrc or .zshrc:

clp() {
  if [[ -z "$1" ]]
  then
    # No input - act as paste
    pbpaste;
  else
    # Input exists - act as copy
    echo "$1" | pbcopy;
  fi
}

To copy use clp "Content" and to paste use clp

Mahdi-Malv
  • 16,677
  • 10
  • 70
  • 117
0

If you're like me and run on a Linux server without root privileges and there isn't any 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!
horta
  • 1,110
  • 8
  • 17
  • I don't see how a lack of root privileges factors into this. – Braden Best May 15 '17 at 17:36
  • 4
    @BradenBest Lack of root privileges means I couldn't install things. – horta May 16 '17 at 18:03
  • 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. – Braden Best May 16 '17 at 18:08
  • 1
    @BradenBest Not sure. Whatever program or service would allow me to perform a copy paste. – horta May 16 '17 at 20:07
  • 1
    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. – Braden Best May 16 '17 at 20:16
0

This function will test what clipboard exists and use it.

To verify copy paste into your shell, and then call the function clippaste:

clippaste () {
    if [[ $OSTYPE == darwin* ]]
    then
            pbpaste
    elif [[ $OSTYPE == cygwin* ]]
    then
            cat /dev/clipboard
    else
            if command -v xclip &> /dev/null
            then
                    xclip -out -selection clipboard
            elif command -v xsel
            then
                    xsel --clipboard --output
            else
                    print "clipcopy: Platform $OSTYPE not supported or xclip/xsel not installed" >&2
                    return 1
            fi
    fi
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
alshaboti
  • 643
  • 8
  • 18
0

If you are using "Windows Terminal" to ssh into a Linux host, you can use the following little script to copy a file to the clipboard of the windows host:

# Clipfile
#  - Sends a file into the Windows Terminal clipboard
printf $'\e]52;c;%s\a' "$(base64 ${1:?})"

I'm not sure if this works with other terminal and console programs???

Thanks to @MrCalvin answer at: https://superuser.com/questions/1705770/copy-data-from-linux-console-to-windowshost-clipboard-using-windows-terminal?newreg=8ad2f39ec3f54a659b0c9e295540bbf1

mrkbutty
  • 489
  • 1
  • 5
  • 13