Last active
October 27, 2017 17:40
-
-
Save NF1198/626de63a1a824ad1d8dc4c52ef36d9f9 to your computer and use it in GitHub Desktop.
a better way to use xclip - https://madebynathan.com/2011/10/04/a-nicer-way-to-use-xclip/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env sh | |
# A shortcut function that simplifies usage of xclip. | |
# - Accepts input from either stdin (pipe), or params. | |
# from: https://madebynathan.com/2011/10/04/a-nicer-way-to-use-xclip/ | |
# author: Nathan Broadbent | |
# | |
# usage: | |
# -$ cd ~ | |
# -$ wget <raw file link> | |
# then add to .bashrc: | |
# if [ -d $HOME/.bash ]; then | |
# find $HOME/.bash/* -name \*\.sh -executable -exec {} \; | |
# fi | |
# | |
# ------------------------------------------------ | |
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" | |
else | |
# If no tty, data should be available on stdin | |
if ! [[ "$( tty )" == /dev/* ]]; then | |
input="$(< /dev/stdin)" | |
# Else, fetch input from params | |
else | |
input="$*" | |
fi | |
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" | |
else | |
# 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" | |
fi | |
fi | |
} | |
# Aliases / functions leveraging the cb() function | |
# ------------------------------------------------ | |
# Copy contents of a file | |
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