Unmount all external drives with bash

Perhaps one of the most annoying reasons to open Finder on mac is to eject hard drives.

This script allows you to avoid that. It will list all drives to be ejected and prompt you for confirmation before unmounting them with diskutil.

Unmounting is done with diskutil unmountDisk, which is safer than eject. If the disk is in use then it will not be ejected.

#! /usr/bin/env bash

# change $internalHD if you have changed the default MacOS system HD name
internalHD="Macintosh HD"
filteredVolumes=()
count=0

echo "Disks to eject:"
for v in /Volumes/*; do
    if [[ $v != *"$internalHD" ]]; then
        echo "• $v"
        filteredVolumes+=("$v")
        count=$((count +1))
    fi
done

if [[ $count == "0" ]]; then
    echo "No disks to eject"
    exit
fi

echo ${disks[*]}

read -p 'Eject ALL the above disks? (Y/N): ' confirm
if [[ $confirm == [yY] || $confirm == [yY][eE][sS] ]]; then
    for v in ${filteredVolumes[*]}; do
        echo "Ejecting $v..."
        diskutil unmountDisk $v
    done
else
    echo 'cancelled'
fi