A while back I wrote this shell function to be able to move files to the trash from the command line on my Mac, rather than condemning them to oblivion with no chance of return. This is in my
.profile
.It's a little hairy looking but it does the job. Note that it attempts to append names with a date stamp if a file/directory with that name already exists in the trash, just as the Finder does.
function del() {An interesting side-effect is that
while [ -n "$1" ]; do
if [ ! -e "$1" ]; then
echo "'$1' not found; exiting"
return
fi
local file=`basename -- "$1"`
# Chop trailing '/' if there
file=${file%/}
local destination=''
if [ -e "$HOME/.Trash/$file" ]; then
# Extract file and extension
local ext=`expr "$file" : ".*\(\.[^\.]*\)$"`
local base=${file%$ext}
# Add a space between base and timestamp
test -n "$base" && base="$base "
destination="/$base`date +%H-%M-%S`_$RANDOM$ext"
fi
echo "Moving '$1' to '$HOME/.Trash$destination'"
\mv -i -- "$1" "$HOME/.Trash$destination" || return
shift
done
}
alias rm='del'
rm <directory>works as well, which is a little uncanny because ordinarily either
rmdir <directory>
(for an empty directory) or rm -rf
is required.2/23/10 update: Handle case where rm options are mistakenly specified.
7/4/08 update: Fixed problem when removing file names containing spaces.
Does it make that annoying click noise too? Well, that's more of a feature if it doesn't.
ReplyDeleteAh, I knew I forgot something. I'm on it.
ReplyDeleteThis just saved me the effort of figuring out how to do this on my own.
ReplyDeleteThanks!
OS X comes with the 'osascript' utility which executes arbitrary AppleScripts from the command line. I wrote a utility a while back that uses osascript to not just simulate the behaviour of trashing files, but to piggyback on Finder's native trashing implementation. Check it out if you're interested: http://alphahelical.com/code/osx/trash/
ReplyDeleteyou can add
ReplyDeleteafplay /System/Library/Components/CoreAudio.component/Contents/Resources/SystemSounds/finder/move\ to\ trash.aif
and it will play Finder's move-to-trash sound