Make Mac eject external drives when going to slumber or sleep/wake

There's a 3rd party app available for exactly this purpose. Jettison app automatically ejects your external drives when you put your MacBook to sleep.

It is a paid app with 15 days of free trial available.


Jettison is an excellent recommendation, and probably the one I would make for most people.

However, if you want to get into all sorts of Mac automation, you'll definitely want to checkout Keyboard Maestro. You can create a macro that will run when the system goes to sleep, and have that macro run a simple shell script like this:

#!/bin/zsh -f 

MNTPNT='/Volumes/Western Digital My Passport for Mac'

COUNT='0'

while [[ -e "$MNTPNT" ]]
do

     /usr/sbin/diskutil unmount "$MNTPNT"

     ((COUNT++))

     [ "$COUNT" -ge "10" ] && exit 0

done

exit 0

that will check to see if the drive is mounted, and if it is, it will try to unmount it.

In fact, it will keep trying if it doesn't succeed.

Keyboard Maestro says that it will only delay sleep for a maximum of 30 seconds, but I added a counter that will give up after 10 tries, because if it hasn't worked by then, it probably isn't going to work.

Anyway, just to show that there are other ways of doing it.

I assume there's a way to try with AppleScript as well, which Keyboard Maestro could also do, but I know shell scripting better than AppleScript.