Search code examples
macosshellunixdiskautomator

Eject all disks and dmg's with Automator script in Mac OS X


I have created an Automator Service to eject all disks in Mac OS X.

find /dev -name "disk[1-9]" -exec diskutil eject {} \;

This works, but I still receive an error message afterwords:

"The action “Run Shell Script” encountered an error."

Anyone know why this is happening?


Solution

  • Run it like this:

    find /dev/disk[1-9] -exec diskutil eject {} \;
    

    The thing is, at least on my Mac, I'm getting this:

    $ find /dev -name disk[1-9]
    find: /dev/fd/3: Not a directory
    find: /dev/fd/4: Not a directory
    /dev/disk2
    

    What happens is find tries to go into /dev/fd/3 which appears to be a directory but it's not, and so you see error messages Not a directory. As a result of this, even though find successfully executes diskutil eject for the files matching the pattern, due to the errors encountered in the process, it will exit with status code 1, indicating an error.

    By using my proposed solution find will only consider the files /dev/disk[0-9] and it will not try to go into subdirectories, as there are none in this case.

    UPDATE

    The exit code of the last command is stored in the $? variable. For example:

    $ find /dev -name disk[0-9]
    find: /dev/fd/3: Not a directory
    find: /dev/fd/4: Not a directory
    /dev/disk2
    $ echo $?
    1
    $ find /dev/disk[0-9]
    /dev/disk2
    $ echo $?
    0
    

    Another way using a for loop would be:

    for f in /dev/disk[1-9]; do diskutil eject $f; done