>

BASH: Multiplatform Scripting – Where’s that command?

Today’s dilema? I Revived an old script and pushed it out to a dozen or so different machines. Not really a big deal, except the script relies on the ‘uname‘ command. Sadly, like many other commands, ‘uname‘ isn’t always in the same place and I hate to rely on $PATH in scripts. Fortunately the solution is simple. I happen to know that it is likely in one of two places (though I check four). With this in mind a simple set of tests can get things running smoothly.

#!/bin/bash
if [ -x "/usr/local/bin/uname" ]; then
    uname="/usr/local/bin/uname"
elif [ -x "/opt/local/bin/uname" ]; then
    uname="/opt/local/bin/uname"
elif [ -x "/bin/uname" ]; then
    uname="/bin/uname"
elif [ -x "/usr/bin/uname" ]; then
    uname="/usr/bin/uname"
else
    echo "$0: command: uname not found"
fi
echo "Platform = `$uname`"

The “-x” test returns true of the file specified is executable and false if it is not. I always throw “/usr/local/bin” and “/opt/local/bin” into the test first because often the native version of a command can be slightly different across platforms. So I will commonly find a GNU/Open Source version and install it where needed. I have found that I prefer to standardize on a version of a command rather than have half a dozen custom scripts everywhere.

banner ad

Comments are closed.