Last active
February 20, 2025 09:33
-
-
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
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
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" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Keep it simple:
copy() { if type -p "$1" ; then "$@" ; else cat "${@:--}" ; fi | pbcopy -Prefer txt ; }