146 Words

Copying and pasting in the Linux terminal is easy with xclip

A simple command

# Copy whatever is piped in to the clipboard
xclip -selection c

Making it a function

I keep forgetting the command, so I added a function to my .bashrc:

# Use it by piping something into copy-to-clipboard
copy-to-clipboard() {
  xclip -selection c
}

# For example:
cat some-file.txt | copy-to-clipboard

On Wayland

xclip only works with X11. Most desktops (GNOME on Fedora and Ubuntu) now use Wayland, where you need wl-copy from the wl-clipboard package:

sudo apt install wl-clipboard    # Debian/Ubuntu
sudo dnf install wl-clipboard    # Fedora

echo "hello" | wl-copy           # copy
wl-paste                         # paste

A function that works on both:

copy-to-clipboard() {
  if [ -n "$WAYLAND_DISPLAY" ]; then wl-copy; else xclip -selection c; fi
}

In the kitty terminal you can also use kitten clipboard, which even works over SSH.