Listing 4

#!/bin/sh
# Define short and longshort option strings with help text
OPT_SHORT="
{Usage: [options]\n}
    a           { -a                    process all\n}
    b           { -b                    use binary mode\n}
    d@          { -d SEC                delay in seconds\n}
"
OPT_LONGSHORT="
    verbose     { -v, --verbose         set verbose mode\n}
    file:       { -f, --file=NAME       use file name\n}
    help        { -h, --help -h         help\n}
"

# Parse command line. Upon failure print "BAD" and "HELP" options. Quotation 
# marks around mgetopt command are needed to preserve spaces in help text
#
eval "`mgetopt short "$OPT_SHORT" longshort "$OPT_LONGSHORT" "$@"`"

if [ "$opt_BAD" ]; then
    echo "$0: mgetopt: failed, bad_opt(s) : $opt_BAD"
    
    # Use 'printf' command to ensure '\n' will be interpreted
    # as a new line
    printf "$0: $opt_HELP"   
    exit 1
fi

if [ "$opt_SHIFT" -eq 0 -o "$opt_help" ]; then

    printf "$0: $opt_HELP"
    exit 0
fi

# Check if the short options are entered
if [ "$opt_a" ]; then echo "a=$opt_a"; fi
if [ "$opt_b" ]; then echo "b=$opt_d"; fi
if [ "$opt_d" ]; then echo "d=$opt_d"; fi

# Check if the longshort options are entered
if [ "$opt_verbose" ]; then echo "verbose=$opt_verbose"; fi
if [ "$opt_file"    ]; then echo "file=$opt_file"; fi

# Shift arguments list and print remaining non-option arguments
shift $opt_SHIFT
i=0
while test "$1"; do
    i=`expr $i + 1` 
    echo "arg[$i]=$1"
    shift
done