Mount and unmount external drives easily via AppleScript

Feb 13, '12 07:30:00AM

Contributed by: Swordfish

I like to eject my external drives because they slow down my mac when they spin up, but I want to have an easy way to access them if I need to. I wrote a little AppleScript that will toggle the mount status of the drive (if it's mounted, it will eject, if it's unmounted, it will mount).

To run the script, use the script menu at the right of the menu bar, or bind it to a hot key using a Quicksilver-type app. Be sure to change 'YourDiskNameHere' to the name of the volume you're working with.

The script can be easily adapted to only eject, or only mount the drive. You can also tweak it to display a Mount/Unmount dialog if you wish.

set diskName to "YourDiskNameHere"
tell application "Finder"
 if disk diskName exists then
  eject disk diskName
 else
  tell current application
   set deviceLine to (do shell script "diskutil list | grep \"" & diskName & "\" | awk '{ print $NF }' }'")
   if deviceLine = "" then
    display dialog "The disk \"" & diskName & "\" cannot be found." buttons {"OK"} default button 1 with title "Error" with icon caution
   end if
   set foundDisks to paragraphs of deviceLine
   repeat with i from 1 to number of items in foundDisks
    set this_item to item i of foundDisks
    if this_item contains "disk" then
     do shell script "diskutil mountDisk /dev/" & this_item
    end if
   end repeat
  end tell
 end if
end tell


[crarko adds: Seems to work fine.

Note: A minor correction to the script was made per request of the author, based on a simplification given in a comment below.]

Comments (19)


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