Automatically eject all disks on sleep, reconnect on wake


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, you can automatically eject disks when you sleep the laptop, meaning you can just put the lid down and go. Disk 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 (should be just two lines):

#!/bin/sh osascript -e 'tell application "Finder" to eject (disks where free space ≠ 0)'

Save the file – call 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”, saved to Desktop too (also just two lines):

#!/bin/sh /usr/sbin/diskutil list | grep -e ' +[0-9]+: +[^ ]+ [^ ]+' | sed 's/.(disk[0-9].)/\1/' | xargs -I{} /usr/sbin/diskutil mount {}

Next, open the Terminal (Applications, Utilities, Terminal), and type 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.

, . Bookmark the permalink. Both comments and trackbacks are currently closed.


  1. ethan
    Posted June 16, 2009 at 3:37 am | Permalink

    Great tip on sleep and wake for drives. Will this code work for networked drives (like my NAS, accessed wirelessly)?

    • Posted June 16, 2009 at 6:35 pm | Permalink

      Hi, Ethan – Sure, I don’t see why not!

    • Esmail
      Posted February 19, 2010 at 3:03 pm | Permalink

      The first script only ejects volumes that are not full (this avoids ejecting optical discs) and can be ejected, but if your remote disk isn’t full I’m not seeing why it would be ejected. For that task you can use the following AppleScript command: tell application "Finder" to eject (every disk whose ejectable is true or local volume is false) which I found in the comments at

  2. Steve
    Posted November 28, 2009 at 10:18 pm | Permalink

    you dont need to keep the txt files on the desktop do you?

  3. Posted December 4, 2009 at 10:15 pm | Permalink

    This is a great idea, I’m going to do this!!!

  4. tom
    Posted January 5, 2012 at 9:37 am | Permalink

    i don’t understand what the grep in the wake file is trying to achieve… either way it returns null on a diskutil list on my system???