Properly Eject Disk?

I created this macro to do the following:

  • Detect when a drive is attached (its gaffer taped to the back of my home monitor and is mounted frequently)
  • Prompt if I want to do a back up which simply launches SuperDuper and Timemachine
  • If no - then it runs a script to eject the drives

The script is where I am stuck. When it runs I physically see the drives disappear from Finder so it looks like they are ejected fine. I, however, get this error still:

check this thread:

Instead of an AppleScript, you could use a shell script.

This script will attempt to unmount "Image" and "Time Machine" drives, if they are mounted.

It will try 5 times before giving up.

#!/usr/bin/env zsh -f

for i in "Image" "Time Machine"
do
	COUNT=0

	while [ -d "/Volumes/$i" ]
	do

		((COUNT++))

		[ "$COUNT" -gt "5" ] && continue

		/usr/sbin/diskutil eject "/Volumes/$i"

	done
done

exit 0

You could use this for other drives by changing "Image" and "Time Machine".

You can add as many as you want, as long as they are "quoted" in the for i in line.

This worked thanks so much!

May I ask how trying 5 times so quickly will help?
Don't you need at least a short delay between tries?

To be honest, 5 times is probably more than you need. It will either work or not, so once or twice would probably be enough, but I figured might as well try a few more, as it will stop as soon as it succeeds.

You could, but in my experience, it takes a few seconds for it to fail, so if it does fail, there has already been a delay.

But if you wanted to add a delay, you could change this line:

/usr/sbin/diskutil eject "/Volumes/$i"

to this

/usr/sbin/diskutil eject "/Volumes/$i"

sleep 3

Change 3 to how many seconds you want to wait.

1 Like