Auto-delete a DMG file when ejecting a disk image

Aug 10, '12 07:30:00AM

Contributed by: tmoswift

While the Mac App Store is great, I still find myself downloading .dmg files and installing plenty of third-party software. I often forget to delete .dmg files after I've installed applications. Here's a script to automatically move the .dmg file to the trash when you eject the disk image.

To use this script, select the mounted volume in the Finder (or in the "Devices" section of the Finder sidebar), and trigger this script via your favorite macro app instead of ejecting the disk image normally.

tell application "Finder"
	set selection_list to selection
	if (count selection_list) < 1 then
		display dialog 
			"Please select a volume mounted from a disk image." with title 
			"No Selection Found" with icon stop 
			buttons ["OK"] default button 1
		return
	end if
	
	set my_selection to item 1 of selection_list
	set my_kind to kind of my_selection
	set my_name to name of my_selection
	
	if my_kind is not "Volume" then
		display dialog 
			"Please select a volume mounted from a disk image file." with title 
			"Selection is not a Disk Image" with icon stop 
			buttons ["OK"] default button 1
		return
	end if
	
	set volume_list to paragraphs of (do shell script "hdiutil info | grep ^/dev/disk | grep -o '/Volumes/.*'")
	set source_list to paragraphs of (do shell script "hdiutil info | grep ^image'-'alias | grep  -o '/.*'")
	
	set match_found to false
	repeat with v from 1 to (count volume_list)
		if "/Volumes/" & my_name = item v of volume_list then
			set match_found to true
			exit repeat
		end if
	end repeat
	
	if match_found is not equal to true then
		display dialog 
			"The selected volume does not appear to be a Disk Image." with title 
			"Could not find Disk Image" with icon stop 
			buttons ["OK"] default button 1
		return
	else
		set my_source to POSIX file (item v of source_list) as alias
		move my_source to the trash
		eject my_selection
		--reveal my_source
	end if
end tell
Matt Rajca has a script that does the reverse: ejects a Disk Image volume when you trash the .dmg file.

Could you simply have a search that looks for old .dmg files in your Downloads folder? Yes, though I often forget to open and install .dmg files right away, so I prefer linking the delete action to the eject.

[kirkmc adds: This works for me if I select a volume in a Finder window, but not in the sidebar. This hint was submitted before Mountain Lion, so perhaps there's something that needs to be tweaked for 10.8. I figured it is worth posting so you all can find what to fix; I'll update the script in the hint if someone provides a solution in the comments.]

Comments (11)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20120728123233584