Pipe to/from the clipboard in Bash script
There's 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
.
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
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