getopt and getopts become very frustrating to use, especially when one has many flags. Keeping the list of options in sync with the case statement used is one thing, but if you need to update a 'usage' function which outputs a listing of all the flags, you easily forget to document your flags.
Take a look at shFlags http://code.google.com/p/shflags/ which is a portable shell library (meaning sh, bash, dash, ksh, zsh on Linux, Solaris, etc.). I wrote to wrap getopt to make the whole process easier. It makes adding new flags as simple as adding one line to your script, and it provides an auto generated usage function.
Here is a simple 'Hello, world!' using shFlags.
#!/bin/sh
# source shflags from current directory
. ./shflags
# define a 'name' command-line string flag
DEFINE_string 'name' 'world' 'name to say hello to' 'n'
# parse the command-line
FLAGS "$@" || exit 1
eval set -- "${FLAGS_ARGV}"
# say hello
echo "Hello, ${FLAGS_name}!"
For OSes that have the enhanced getopt that supports long options (e.g. Linux), you can do:
$ ./hello_world.sh --name Kate
Hello, Kate!
For the rest, you must use the short option:
$ ./hello_world.sh -n Kate
Hello, Kate!
Adding a new flag is as simple as adding a new DEFINE_ call
.
kate