Matt Rajca

blog projects github twitter email

Auto-Ejecting Disc Image Files Dragged to the Trash

September 05, 2011

Even with the growth of the Mac App Store, I still find myself constantly downloading, mounting and eventually deleting DMGs. Almost just as frequently, I am greeted with the following dialog whenever I try to empty the Trash with a mounted disc image file inside it:

Trash Eject

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, that will be the current user's Trash. Our Folder Action will eject any mounted disc image files moved to the Trash.

  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.

eject.py:

    
    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
    

Once your new Folder Action is saved, any mounted disc image files dragged to the Trash will be ejected automatically.