This is one of those "oh duh!" things that I wish I'd realized earlier. I have a few shell scripts that I'd like to keep on the Many Tricks cloud server, as I'd like to use them on multiple Macs.
But depending on which Mac is running the script, I might need to use unique code. The path to my Dropbox folder, for example, is different on my laptop and my iMac. So if I want to reference the path to my Dropbox folder, it needs to be different on each Mac. I couldn't figure out how to make that happen with just one script, so I'd been using near-identical versions on each Mac.
Then I remembered the hostname command, which returns the name of the machine running the command:
$ hostname Robs-rMBP.local
And that was the tidbit of "duh!" knowledge I needed. With that, and the case statement, I can make my shell scripts use code based on which machine runs them. For instance, I can set unique paths for the script that grabs the latest versions of our apps from our server:
myhost=`hostname` case $myhost in Robs-iMac.local) theHub=/path/to/apps/on/manytricks/cloud ; theDest=/path/to/local/copy/of/apps ;; Robs-rMBP.local) theHub=/different/path/to/apps/on/manytricks/cloud ; theDest=/other/path/to/local/copy/of/apps ;; *) echo "Sorry, unrecognized Mac." ; exit ;; cp $theHub/$appname $theDest/$appname etc
Another nice thing about this is the script won't run on a Mac I haven't set up yet, thanks to the #) bit. And if I happen to rename one of my Macs, the script will also fail to run, letting me know I need to update the name in the script.
A simple tip, but one I'd managed to overlook for years. Now that I've written it up, that shouldn't happen again.
This behaviour can be upended by changing the hostname, you could do the same thing by getting the machine's serial number, which would leave less room for user-tampering.
Instead of calling
hostname
and assigning it to a variable, you can use the existing variable $HOSTNAME (bash, sh) or $HOST (zsh script). Using the built-in env variable is more efficient and safer.case $HOSTNAME in
Robs-iMac.local) ....
....
Comments are closed.