When I’m at home, my MacBook Pro is hooked up to an external display, a couple of hard drives, and other peripherals. When I need to go on the road, I put it to sleep, unplug all the peripherals, and away I go.
There’s only one problem: Unplugging a hard drive can corrupt its filesystem if it’s still mounted. To prevent that from happening, I wrote a script that automatically unmounts all drives. As an added bonus, the script fails if any of those drives are busy and can’t be unmounted, warning me to take additional action before hitting the road. Here it is:
tell application “Finder” eject (every disk whose ejectable is true) end tell
In most cases, this simple script works great, but it suffers from a few drawbacks:
- It ejects not only hard drives, but optical discs as well, which is usually not what I want.
- It won’t eject remotely mounted drives, such as NFS or AFP mounts.
- It won’t work if Finder is not running, which may be the case for PathFinder users like myself.
To fix these issues, I split the script into two parts, one for local drives and one for remote drives, and I rewrote it so that optical discs would be left alone. Here’s the part that unmounts local drives:
-- Set this list to the names of the local drives -- you want to unmount set local_drives to [“Backup drive”, “Clone”] repeat with drive in local_drives set drive to “/Volumes/” & drive set driveExists to false try -- Ignore AppleScript warnings do shell script “test -d ” & ¬ quoted form of drive -- Test completed successfully; drive exists set driveExists to true end try if driveExists then -- Eject the drive do shell script "umount " & ¬ quoted form of drive end if end repeat
And here’s the part that unmounts the remote drives:
-- Set this list to the names of the remote drives -- you want to unmount set remote_drives to [“DreamHost”, “DOC”] repeat with drive in remote_drives set drive to “/Volumes/” & drive do shell script “umount ” & ¬ quoted form of drive end repeat
I don’t eject optical drives, but if for some reason you need to do so, here’s how:
-- This will eject the optical disc in the -- primary (built-in) drive do shell script “drutil -drive 1 eject” -- This will eject all discs in all optical drives do shell script “drutil eject”
For a downloadable version of these scripts, see my AppleScript page.