Xclip could be a great commandline tool for pulling things into your clipboard. I say ‘could be’ because remember the options needed to use it is as bad as using tar. I was digging around for a solution, and found a great bash script at madebynathan that solves the problem.

The madebynathan site suggests adding the script to your ~/.bashrc file. I like to keep my bashrc a bit cleaner, so instead I saved the script as ~/.cp.bashrc so that I can easily remember what chunk of code causes ‘cp’ to work.


  • Pipe anything to the clipboard
$ tail -n 100 /var/log/apache2/error.log | cb
# => Copied to clipboard: [Sun Oct 02 08:02:08 2011] [notice] Apache/2.2.17 (Ubuntu) configured -- resumin...
  • Copy the contents of a file to the clipboard
$ cbf ~/.ssh/id_rsa.pub
# => Copied to clipboard: ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAnwaNIuOhZzUeR6/xEEudXt3zEh91dawhkkKx8p/+4Bw9...
  • Type straight into the clipboard
$ cb This is some unquoted text.
# => Copied to clipboard: This is some unquoted text.

No options, no man pages.

Installing it

If you think this looks handy, add the line

source ~/.cp.bashrc

to your ~/.basrc file. Then save the below code section to ~/.cp.bashrc, and rock the easy xclip magic

# A shortcut function that simplifies usage of xclip.
# - Accepts input from either stdin (pipe), or params.
# ------------------------------------------------
cb() {
  local _scs_col="\e[0;32m"; local _wrn_col='\e[1;31m'; local _trn_col='\e[0;33m'
  # Check that xclip is installed.
  if ! type xclip > /dev/null 2>&1; then
    echo -e "$_wrn_col""You must have the 'xclip' program installed.\e[0m"
  # Check user is not root (root doesn't have access to user xorg server)
  elif [[ "$USER" == "root" ]]; then
    echo -e "$_wrn_col""Must be regular user (not root) to copy a file to the clipboard.\e[0m"
    # If no tty, data should be available on stdin
    if ! [[ "$( tty )" == /dev/* ]]; then
      input="$(< /dev/stdin)"
    # Else, fetch input from params
    if [ -z "$input" ]; then  # If no input, print usage message.
      echo "Copies a string to the clipboard."
      echo "Usage: cb <string>"
      echo "       echo <string> | cb"
      # Copy input to clipboard
      echo -n "$input" | xclip -selection c
      # Truncate text for status
      if [ ${#input} -gt 80 ]; then input="$(echo $input | cut -c1-80)$_trn_col...\e[0m"; fi
      # Print status.
      echo -e "$_scs_col""Copied to clipboard:\e[0m $input"
# Aliases / functions leveraging the cb() function
# ------------------------------------------------
# Copy contents of a file
function cbf() { cat "$1" | cb; }  
# Copy SSH public key
alias cbssh="cbf ~/.ssh/id_rsa.pub"  
# Copy current working directory
alias cbwd="pwd | cb"  
# Copy most recent command in bash history
alias cbhs="cat $HISTFILE | tail -n 1 | cb"