Skip to content

Instantly share code, notes, and snippets.

@ttscoff
Last active September 11, 2019 14:07
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ttscoff/16dcf9f6dcd9f4c46bd9 to your computer and use it in GitHub Desktop.
Save ttscoff/16dcf9f6dcd9f4c46bd9 to your computer and use it in GitHub Desktop.
Intelligently copy command results, text file, or raw input/arguments to OS X clipboard
copy() {
if [[ $1 =~ ^-?[hH] ]]; then
echo "Intelligently copies command results, text file, or raw text to"
echo "OS X clipboard"
echo
echo "Usage: copy [command or text]"
echo " or pipe a command: [command] | copy"
return
fi
local output
local res=false
local tmpfile="${TMPDIR}/copy.$RANDOM.txt"
local msg=""
if [[ $# == 0 ]]; then
output=$(cat)
msg="Input copied to clipboard"
res=true
else
local cmd=""
for arg in $@; do
cmd+="\"$(echo -en $arg|sed -E 's/"/\\"/g')\" "
done
output=$(eval "$cmd" 2> /dev/null)
if [[ $? == 0 ]]; then
msg="Results of command are in the clipboard"
res=true
else
if [[ -f $1 ]]; then
output=""
for arg in $@; do
if [[ -f $arg ]]; then
type=`file "$arg"|grep -c text`
if [ $type -gt 0 ]; then
output+=$(cat $arg)
msg+="Contents of $arg are in the clipboard.\n"
res=true
else
msg+="File \"$arg\" is not plain text.\n"
fi
fi
done
else
output=$@
msg="Text copied to clipboard"
res=true
fi
fi
fi
$res && echo -ne "$output" | pbcopy -Prefer txt
echo -e "$msg"
}
@nabin-info
Copy link

Keep it simple:

copy() { if type -p "$1" ; then "$@" ; else cat "${@:--}" ; fi | pbcopy -Prefer txt ; }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment