Thursday, October 1, 2009

Automatically Empty Trash When Ejecting Removable Drive (Mac)

Problem:  When I “delete” pictures from an SD card on a MacBook without emptying the Trash, the SD card is still full when I insert it back into the digital camera.  Although not nearly as annoying, the same thing happens when I forget to empty the Trash before ejecting a USB drive.

Solution:  There may be a much better way of doing this, but I searched Google for a better solution.  So I wrote this little bash script that would delete the .Trashes folder and other things Mac OS X tries to hide on there.  The bash script below will intercept the command to eject a volume, do some checking on it, empty the trash on that drive, then pass control to the real eject command.  The main "trick" is to make sure the drive is formatted as MSDOS, which will be any removable drive you are using in both Mac OS X and Windows. 
You will need open Terminal, rename /sbin/umount to /sbin/umount2, then copy the contents below into a file and save it as /sbin/umount.  This has been tested in Leopard and Snow Leopard.

Disclaimer:  I am not responsible if you mess something up.  Perform these steps at your own risk.  I intentionally didn't explain step by step how to make this work.  If you have no idea what the sentence in red means, then you should not attempt this hack. If you are an old school Linux/Unix user or familiar with the Terminal app then you should have no problem getting this to work.


#!/bin/bash

if [ $# -gt 0 ]
then
  vol=`df -T msdos | grep "$1"`

  if [ "$vol" != "" ]
  then
    nlen=`expr ${#1} - ${#1} - ${#1}`

    if [ "${vol:(nlen)}" == "$1" ]
    then
      /bin/rm -rf "$1/.Trashes"
      /bin/rm -f  "$1/._.Trashes"
      /bin/rm -rf "$1/.fseventsd"
      /bin/rm -rf "$1/.Spotlight-V100"
    fi
  fi
fi

/sbin/umount2 "$1"

No comments:

Post a Comment