Pipe To/From the Clipboard in a Bash Script

Pipe to/from the clipboard in a Bash script

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

Pipe to/from the clipboard in a Bash script

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

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

I always wanted to do this and found a nice and easy way of doing it. I wrote down the complete procedure just in case anyone else needs it.

First install a 16 kB program called xclip:

sudo apt-get install xclip

You can then pipe the output into xclip to be copied into the clipboard:

cat file | xclip

To paste the text you just copied, you shall use:

xclip -o

To simplify life, you can set up an alias in your .bashrc file as I did:

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

If you want to paste somewhere else other than a X application, try this one:

cat file | xclip -selection clipboard

Copy shell script output to clipboard

That may depend on the environment you're using. With Gnome at least (I haven't tried the others but it may work), you can pipe your output as follows:

echo 123 | xclip
echo 123 | xclip -sel clip

The first goes to the mouse clipboard, the second to the "normal" clipboard.

How to get value from Clipboard in bash

On Mac OS, pbcopy/pbpaste:

echo "Set the clipboard" | pbcopy

clipboard="$(pbpaste)"

On Linux with X11, xclip.

echo "Set the clipboard" | xclip

clipboard="$(xclip -o)"

Copy the manual to clipboard

pbcopy accepts its input on stdin so you can just pipe to it, like

man scp | pbcopy

You may also want to filter the man output to remove some formatting that does not work in plain text, like:

man scp | col -b | pbcopy

Info from this answer



Related Topics



Leave a reply



Submit