Tuesday, April 8, 2008

Move to Trash from the Mac Command Line

I was about to make a lengthy comment to a post on Life Hacker and decided to put most of it here instead. That site is seriously starting to take over my life.

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() {
while [ -n "$1" ]; do
if [ ! -e "$1" ]; then
echo "'$1' not found; exiting"

local file=`basename -- "$1"`

# Chop trailing '/' if there

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"

echo "Moving '$1' to '$HOME/.Trash$destination'"
\mv -i -- "$1" "$HOME/.Trash$destination" || return

alias rm='del'
An interesting side-effect is that
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.


  1. Does it make that annoying click noise too? Well, that's more of a feature if it doesn't.

  2. Ah, I knew I forgot something. I'm on it.

  3. This just saved me the effort of figuring out how to do this on my own.


  4. 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/

  5. you can add

    afplay /System/Library/Components/CoreAudio.component/Contents/Resources/SystemSounds/finder/move\ to\ trash.aif

    and it will play Finder's move-to-trash sound