macOS Terminal – Run Shell Script on Specified External HDD Mount

command linemacosterminal

I keep some files on an external HDD and I've wanted to know what is currently on it without connecting it.

I've modified this command to get a .txt file with tree-like structure of my folders on that HDD uploaded to my iCloud Drive when I connect it to my MBP.

This is my edited command which I have saved as .sh, now saving the file to desktop:

ls -R /Volumes/2TB/ sed -e '/^[^:]*$/d' -e 's/://' -e 's/[^-][^\/]*\//--/g' -e 's/^/ /' -e 's/-/|/' > /Volumes/SSD/Users/V/Desktop/File.txt

So far I've made a shortcut in BTT which runs the script but I would like it to run when I connect that HDD.

Someone suggested that I can could create a launchd with the StartOnMount key.
The problem is, as far as I understand from this thread, it's not possible to set up with specified volume.

Any ideas?

Best Answer

In this example the output of df is piped to grep which is looking to match the hard disk mount point- /Volumes/2TB. The exit status of grep determines the outcome of the condition and the ! reverses the logic.

if ! df | grep -q '\/Volumes\/2TB$'
then 
    exit 0
fi

In a sentence this says, if grep does not match /Volumes/2TB then exit the script.

I would write the script like this to put it all together.

#!/bin/sh
#
#
if ! df | grep -q '\/Volumes\/2TB$'
then 
    exit 0
fi

ls -R /Volumes/2TB/ |
    sed -e '/^[^:]*$/d' \
        -e 's/://' \
        -e 's/[^-][^\/]*\//--/g' \
        -e 's/^/ /' \
        -e 's/-/|/' >/Volumes/SSD/Users/V/Desktop/File.txt