Automatically eject/mount disks on sleep/wake

Apr 04, '08 07:30:00AM

Contributed by: miketyson

Using a laptop with permanent external drives can be a bit annoying when you leave the desk -- you have to manually eject all your devices, otherwise you get that dreaded 'Device Removal' dialog. With a little bit of Terminal magic, though, you can automatically eject disks when you sleep the laptop, meaning you can just put the lid down and go. Disks are also reconnected automatically on wake, for when you're just sleeping the computer without going places.

It's all thanks to a little utility by Bernhard Baehr called SleepWatcher, which runs in the background and is triggered by sleep and wake events, calling scripts to perform required actions. Download and install SleepWatcher and its StartupItem. Next, you're going to create ~/.sleep and ~/.wakeup files which SleepWatcher will call upon.

Pull up your favourite text editor and paste the following in:

#!/bin/sh
osascript -e 'tell application "Finder" to eject (disks where free space ≠ 0)'
Save the file (name it sleep.txt and save it to the Desktop); make sure it's plain text! Then put the following in another file, called wakeup.txt, also saved to the Desktop:
#!/bin/sh
/usr/sbin/diskutil list | grep -e ' \+[0-9]\+: \+[^ ]\+ [^ ]\+' | sed 's/.*\(disk[0-9].*\)/\1/' | xargs -I{} /usr/sbin/diskutil mount {}
Next, launch Terminal (in Applications » Utilities) and type in the following:
$ mv Desktop/sleep.txt .sleep
$ chmod a+x .sleep
$ mv Desktop/wakeup.txt .wakeup
$ chmod a+x .wakeup
Now, whenever you sleep your machine, the external drives will be ejected automatically. When the machine wakes again, all connected external drives will be reconnected.

[robg adds: I haven't tested this one...]

Comments (15)


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