René Nyffenegger's collection of things on the web
René Nyffenegger on Oracle - Most wanted - Feedback -
 

getopts [shell]

getopts option-string variable-name [argument_1 .. argument_n]
Calling getopts assigns the next command line option to the variable named variable-name. Also, the index of the next argument is assigned to $OPTIND.
If an option requires an argument, the value of the argument is placed into $OPTARG.
getopts returns 0 as long as it has read an argument the argument is not the special string --. So, getopts can easily be used together with while.
The following example can be called with the options -a, -p and -q. -p requires an value, something like -psomevalue -q or -a -phello.
OPT_A=0
OPT_P=0
OPT_Q=0

while getopts ap:q option_read; do
  case $option_read in
    a)  OPT_A=1       ;;
    p)  OPT_P=1
        VAL_P=$OPTARG ;;
    q)  OPT_Q=1       ;;
  esac
done

echo $OPTIND

shift `expr $OPTIND - 1`

if [ $OPT_A -eq 1 ]; then
  echo Option A is used
else
  echo Option A is not used
fi

if [ $OPT_P -eq 1 ]; then
  echo Option P''s value is $VAL_P
else
  echo Option P is not used
fi

if [ $OPT_Q -eq 1 ]; then
  echo Option P is used
else
  echo Option P is not used
fi

echo The rest is $@