Make Copying to the Clipboard From the Terminal in Mac and Linux Smoother

July 11, 2025 full-stack note-to-self

I use both Mac and Linux. I'm using to copying things to my clipboard from a terminal using pbcopy, so this helper makes it easier because I don't have to remember the linux flavor of the command.

Drop this in your ~/.bashrc and source it:

# macOS-style clipboard helpers for Linux
# requires either xclip or xsel

# pbcopy: copy file contents or stdin into the X clipboard
pbcopy() {
  if command -v xclip >/dev/null 2>&1; then
    if [ $# -gt 0 ]; then
      # you passed one or more filenames
      xclip -selection clipboard -i "$@"
    else
      # no args → read from stdin
      xclip -selection clipboard -i /dev/stdin
    fi
  elif command -v xsel >/dev/null 2>&1; then
    # xsel needs stdin redirection; filenames handled via cat
    if [ $# -gt 0 ]; then
      cat "$@" | xsel --clipboard --input
    else
      xsel --clipboard --input
    fi
  else
    echo "Error: install xclip or xsel to use pbcopy." >&2
    return 1
  fi
}

# pbpaste: dump the X clipboard to stdout
pbpaste() {
  if command -v xclip >/dev/null 2>&1; then
    xclip -selection clipboard -o
  elif command -v xsel >/dev/null 2>&1; then
    xsel --clipboard --output
  else
    echo "Error: install xclip or xsel to use pbpaste." >&2
    return 1
  fi
}
These posts are for my own understanding. Reader beware. Info may be wrong but it reflects my current understanding.