brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: diskutil eject takes every volume of a disk offline before you pull the cable

Disk
~/tips/tip-macos-diskutil-eject

diskutil eject disk4

Unmounts every volume on a disk and takes it offline, ready to unplug.

Ejecting from Finder is fine when the drive shows up in the sidebar. From the terminal, or in a script that runs after a backup, I want one command that safely releases the whole disk.

diskutil has three verbs for this, and they do different things. unmount unmounts a single volume. unmountDisk unmounts all volumes on a disk, but the disk stays attached, which is what you want right before you erase or partition it. eject goes one step further: the disk goes offline and removable media becomes safe to unplug.

diskutil eject disk4

You can find the right number with diskutil list external physical, which only shows plugged-in drives. On an external SSD with two APFS volumes, the command above unmounts both and takes the disk offline in one go.

For a script I’d write it like this, so a failed eject doesn’t go unnoticed:

diskutil eject disk4 || echo "disk4 is still in use"

The caveat is the force option. diskutil unmountDisk force disk4 exists, but the man page calls it “less kind to any open files”, and an app that was still writing can leave a damaged file behind. My advice is to close the app that holds the disk first and use force only when you’re sure nothing is writing. Also, an unmount can take a few seconds while other processes approve it and data is flushed; diskutil gives up after about a minute in most situations.

Further reading: diskutil man page (SS64 mirror of Apple's man page)

More Disk tips sudo e2freefrag /dev/sdb1 sudo smartctl -a --json /dev/sda | jq '.smart_status.passed' lsscsi -s udisksctl power-off -b /dev/sdX du -sh — .[!.]* * 2>/dev/null | sort -h All Disk tips (44) All topics

Link