Skip to content

Instantly share code, notes, and snippets.

@keithws
Last active August 29, 2015 14:14
Show Gist options
  • Save keithws/d88da41e67670d6c3b2b to your computer and use it in GitHub Desktop.
Save keithws/d88da41e67670d6c3b2b to your computer and use it in GitHub Desktop.
trash bash script
#
# 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
}
@keithws
Copy link
Author

keithws commented Jan 29, 2015

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