Last active
August 29, 2015 14:14
-
-
Save keithws/d88da41e67670d6c3b2b to your computer and use it in GitHub Desktop.
trash bash script
This file contains hidden or 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
# | |
# trash command | |
# move files to the trash | |
# | |
function trash { | |
if [[ "$@" == "" ]] | |
then | |
echo "usage: trash file ..." | |
return 64 | |
fi | |
result=0 | |
file_count=0 | |
for argument in "$@" | |
do | |
# ignore arguments that begin with a dash | |
if [[ "x$argument" == x-* ]] | |
then | |
continue | |
fi | |
# count number of arguments that look like files | |
(( file_count++ )) | |
# build a full path to the file specified | |
if [[ -d "$argument" ]] | |
then | |
pushd "$argument" >/dev/null | |
file_path="$(pwd)" | |
popd >/dev/null | |
elif [[ -e $argument ]] | |
then | |
pushd "$(dirname "$argument")" >/dev/null | |
file_path="$(pwd)/$(basename "$argument")" | |
popd >/dev/null | |
else | |
echo "trash: $argument: No such file or directory" >&2 | |
result=1 | |
continue | |
fi | |
# use the Finder to trash files correctly | |
if [[ "x$file_path" != "x" ]] | |
then | |
osascript <<APPLESCRIPT | |
tell application "Finder" | |
move POSIX file "$file_path" to trash | |
end tell | |
return | |
APPLESCRIPT | |
# capture unsuccessful exit codes | |
if [[ "$?" -ne 0 ]] | |
then | |
result=$? | |
fi | |
fi | |
done | |
# when none of the arguments look like files | |
# show how to use the command | |
if [[ "$file_count" -eq 0 ]] | |
then | |
echo "usage: trash file ..." | |
return 64 | |
fi | |
return $result | |
} |
It also meant to be compatible with rm, so you can alias rm=trash.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I add this to my bash profile so I can easily move files to the trash on Mac OS X from the command line.