Shell scripting patterns: configuration and option parsing

Adhering to software patterns lowers the threshold for doing the right thing, even when the quick hack beckons. This is particularly true in shell script handling of options and configuration. Essentially, the top of all scripts should look like this:

OPTION1="default_value"

. /etc/my.conf

function usage() {
    echo "./dascript [-o <value>] -p <value>"
    echo " -o: set the value of option1"
    echo " -p: set the value of option2"
}

while getopts "ho:p:" opt ; do
    case "$opt" in
    o) OPTION1=$OPTARG
    p) OPTION2=$OPTARG
    h) usage ; exit 0 ;;
    *) usage >&2 ; exit 1 ;;
    esac
}

[ -n "$OPTION2" ] || {
    echo "Please supply -p <value>"
    usage
    exit 1
} >&2

Copy the above example each time you get to the point where you need any configuration whatever for a script. It's much easier than trying to cheat.

So what is going on?

  1. List all parameter with their default values.
  2. Source a configuration file, which will overwrite the default value.
  3. Define a function usage that prints all available options (so that we can use it when parsing options).
  4. Parse options supplied on the commandline to allow overriding the configuration file.
  5. Verify that options have good values, including mandatory options.

The only time this pattern fails is when you need to allow supplying the name of the configuration file.