Developing software in the Real World

Prevent an external drive from auto mounting on macOS

I have an external drive attached to the USB hub on my Thunderbolt Display that I use to clone my laptop’s internal drive every night using the schedule feature of SuperDuper!. At the appointed time, SuperDuper! will mount the external drive, clone the internal drive and then unmount the external drive again which is very convenient.

However, whenever I plug in my laptop, the drive automatically mounts. This doesn’t particularly worry me, but when I unplug my laptop from the display, I either have to unmount the drive first or I get an error. Today, after mumble mumble years of this, I finally decided to solve this by stopping this drive auto mounting.

To prevent a drive auto mounting on macOS, you add a line to /etc/fstab like this:

To obtain the UUID and TYPE, you can use diskutil info {device identifier} and look up the Volume UUID and Type (Bundle) values. You can look up the {disk identifier} using diskutil list.

For a clone of macOS that’s Catalina or more recent, there are two volumes that make up the one logical volume: the main read-only volume and also the “- Data” volume which contains everything that’s read write. For my external drive, these two volumes are called “Swiftsure Clone” and “Swiftsure Clone – Data”. Using diskutil list, I can see that “Swiftsure Clone” is disk4s1 and “Swiftsure Clone – Data” is disk4s5, so I need both UUIDs and types from diskutil info to craft the /etc/fstab entries.

This is far too much to remember for next time I replace this drive!

So I wrote a script, no_automount, that does it for me. To use it , I simply type: ~/bin/no_mount {name of drive} and it enters the two entries:

We can then prove that it got it right by looking at the file:

and now my external drive no longer mounts when I plug it in!

The Script

As with all good automation projects, writing the script was much more work than doing it manually once!

no_automount:

I’ve comprehensively commented it in the hope that I’ll be able to remember how it works next time I need to look at it.

The most tricky bit was extracting the volume name from the middle of the line in the output of diskutil list to use a comment in /etc/fstab. In the end, I used regex to capture from the provided volume name to the end of the line and then a reverse cut to take off the last three fields. This feels a little inelegant, but it works!

If you need to prevent an external drive from automatically mounting when you plug it in, maybe this will help you too.

Thoughts? Leave a reply

Your email address will not be published. Required fields are marked *