Sep 05 2011
∞
Auto-Ejecting Disc Image Files Dragged to the Trash
Even with the growth of the Mac App Store, I still find myself constantly downloading, mounting, and eventually trashing DMGs. Almost just as frequently, I am greeted with the following dialog whenever I try to empty the Trash with mounted disc image files inside it:

Fortunately for us, we can overcome this annoyance by creating a Folder Action in Automator. Folder Actions run whenever the contents of a specified directory change – in this case, the current user’s Trash. Any mounted disc image files found inside the Trash will get ejected automatically by our Folder Action.
- Open Automator, which can be found inside the
Applicationsdirectory. - Create a new document and select ‘Folder Action’ from the template chooser.
- Click on the ‘Choose folder’ pop-up button and select ‘Other…” from the menu that appears.
- When the ‘open’ panel comes up, hit Shift+⌘+G and enter
~/.Trashin the location field; click ‘Go’, followed by ‘Choose’. - Drag a new instance of the ‘Run Shell Script’ action (listed under the Utilities group) from the Library into your workflow.
- Set the action’s shell to
/usr/bin/pythonand its input type to ‘as arguments’. - Finally, replace the contents of the placeholder script with the one listed below.
import string, os, sys
lines = os.popen("hdiutil info").readlines()
should_eject = False
for line in lines:
if line.startswith("image-alias"):
path = line.split(":")[1]
image_path = path.lstrip().rstrip()
if image_path in sys.argv:
should_eject = True
elif line.startswith("/dev/") and should_eject is True:
os.popen("hdiutil eject %s" % line.split()[0])
should_eject = False
elif line.startswith("###"):
should_eject = False
After your new Folder Action is saved, any mounted disc image files dragged to the Trash will get ejected automatically.