Mac – Auto unmount time machine drive on sleep

hard drivesleep-waketime-machine

I keep a drive attached to my MacBook for Time Machine backups when I'm at my desk. I also regularly work from places other than my desk. Most of the time, if I close the laptop lid I intend to leave my desk, so I need to unmount the drive. Is there any way to automate this, so that the OS automatically unmounts the drive before sleep? I figure my options are

  1. Just be a bad computer user and unplug the drive. (yikes)
  2. Manually remember to unmount the driveā€¦ This takes 15-20 seconds altogether, and I'll forget at least some of the time.
  3. Figure out how to make it automatic.

Best Answer

You can use ioreg to test if your lid is closed or open:

ioreg -r -k AppleClamshellState | grep AppleClamshellState

No= Lid is open Yes= Lid is closed

You can use diskutil unmount /dev/<mydisk> to unmount the TimeCapsule. Use diskutil list to find the disk location of the TimeCapsule.

Using if statements you can automate the job:

if [[ $(ioreg -r -k AppleClamshellState | grep AppleClamshellState | grep Yes) ]]; then echo Lid Closed; diskutil unmount /dev/<mydisk>; fi

You can use launchd to set up a automated job that is repeated for example every second (see how to here: http://alvinalexander.com/mac-os-x/mac-osx-startup-crontab-launchd-jobs)