Skip to content

Instantly share code, notes, and snippets.

@FreedomBen
Created June 13, 2024 14:50
Show Gist options
  • Save FreedomBen/83abf6c597a209a28dba522658aa0ca5 to your computer and use it in GitHub Desktop.
Save FreedomBen/83abf6c597a209a28dba522658aa0ca5 to your computer and use it in GitHub Desktop.
cb function and derivatives
### These are bash functions meant to be run directly in a shell.
### You need to source this file in your shell. Running it won't do anything
# A shortcut function that simplifies usage of xclip.
# - Accepts input from either stdin (pipe), or params.
cb()
{
local SUCCESS_COLOR="\e[0;32m"
local WARNING_COLOR="\e[1;31m"
local TRUNCATE_COLOR="\e[0;33m"
local RESET_COLOR="\e[0m"
# Check that xclip is installed.
if ! command -v xclip &>/dev/null; then
echo -e "${WARNING_COLOR}You must have the 'xclip' program installed.${RESET_COLOR}"
return 1
fi
# Check user is not root (root doesn't have access to user xorg server)
if [[ "$USER" == "root" ]]; then
echo -e "${WARNING_COLOR}Must be regular user (not root) to copy a file to the clipboard.${RESET_COLOR}"
return 1
fi
# Determine the input source
if ! [[ "$(tty)" == /dev/* ]]; then
input="$(</dev/stdin)"
else
input="$*"
fi
# If no input, print usage message
if [ -z "$input" ]; then
echo "Copies a string to the clipboard."
echo "Usage: cb <string>"
echo " echo <string> | cb"
return 1
fi
# 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)${TRUNCATE_COLOR}...${RESET_COLOR}"
fi
# Print status
echo -e "${SUCCESS_COLOR}Copied to clipboard:${RESET_COLOR} $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"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment