Matt Rajca

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:

Disc Image in Trash

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.

  1. Open Automator, which can be found inside the Applications directory.
  2. Create a new document and select ‘Folder Action’ from the template chooser.
  3. Click on the ‘Choose folder’ pop-up button and select ‘Other…” from the menu that appears.
  4. When the ‘open’ panel comes up, hit Shift+⌘+G and enter ~/.Trash in the location field; click ‘Go’, followed by ‘Choose’.
  5. Drag a new instance of the ‘Run Shell Script’ action (listed under the Utilities group) from the Library into your workflow.
  6. Set the action’s shell to /usr/bin/python and its input type to ‘as arguments’.
  7. 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.

19 notes

  1. mattrajca posted this
Page 1 of 1