X11
If using X11 (the most common GUI on traditional Unix or Linux based systems), to copy the content of a file to the X11 CLIPBOARD selection without displaying it, you can use the xclip
or xsel
utility.
xclip -sel c < file
Or:
xsel -b < file
to store the content of file
as the CLIPBOARD X11 selection.
To store the output of a command:
mycommand | xclip -sel c
mycommand | xsel -b
Note that it should be stored using an UTF-8 encoding or otherwise pasting won't work properly. If the file
is encoded using an another character set, you should convert to UTF-8 first, like:
<file iconv -f latin1 -t utf8 | xclip -sel c
for a file encoded in latin1/iso8859-1.
xsel
doesn't work with binary data (it doesn't accept null bytes), but xclip
does.
To store it as a CUT_BUFFER (those are still queried by some applications like xterm
when nothing claims the CLIPBOARD or PRIMARY X selections and don't need to have a process running to serve it like for selections), though you probably won't want or need to use that nowadays:
xprop -root -format CUT_BUFFER0 8s -set CUT_BUFFER0 "$(cat file)"
(removes the trailing newline characters from file
).
GNU screen
GNU screen
has the readbuf
command to slurp the content of a file into its own copy-paste buffer (which you paste with ^A]
). So:
screen -X readbuf file
Apple OS/X
Though Apple OS/X can use X11. It doesn't by default unless you run a X11 application. You would be able to use xclip
or xsel
there as OS/X should synchronise the X11 CLIPBOARD selection with OS/X pasteboard buffers, but that would be a bit of a waste to start the X11 server just for that.
On OS/X, you can use the pbcopy
command to store arbitrary content into pasteboard buffers:
pbcopy < file
(the file's character encoding is expected to be the locale's one). To store the output of a command:
mycommand | pbcopy
Shells
Most shells have their own copy-paste buffers. In emacs mode, cut and copy operations store the copied/cut text onto a stack which you yank/paste with Ctrl-Y, and cycle through with Alt+Y
zsh CUTBUFFER/killring
In zsh
, the stack is stored in the $killring
array and the top of the stack in the $CUTBUFFER
variable though those variables are only available from Zsh Line Editor (zle) widgets and a few specialised widgets are the prefered way to manipulate those.
Because those are only available via the ZLE, doing it with commands is a bit convoluted:
zmodload zsh/mapfile
zle-line-init() {
if [ -n "$FILE_TO_COPY" ]; then
zle copy-region-as-kill $mapfile[$FILE_TO_COPY]
unset FILE_TO_COPY
fi
}
zle -N zle-line-init
file-copy() FILE_TO_COPY=$1:A
The zle-line-init
special widget is executed once at the start of each new command prompt. What that means is that the file will only be copied at the next prompt. For instance, if you do:
file-copy file; sleep 2
The file will only be copied after those 2 seconds.