#!/bin/bash
#
# Syntax: getopts OPTION_STRING OPTION_VARIABLE
#
# 'getopts' parses options provided in a command line using the standard
# convention (one dash for single character, two dashes for full option
# name, single-letter options can be concatenated, etc.)
#
# Each time 'getopts' is invoked, it places the value of the next option in
# the variable specified as its second argument and the index of the next
# argument to be processed in the shell variable OPTIND.
#
# If an option character not contained in the optstring operand is found,
# the variable is set to '?'.
#
# When no more oprtions are found, 'getopts' exits with a return value > 0.
#
# You use a colon ':' in two situations:
#   1. After an option, to indicate that it requires an argument. The
#      argument is stored in the OPTARG variable.
#   2. At the beginning of the options string, to indicate silent error
#      reporting.

while getopts "dDhLUzk" opt
do
     case $opt in
          (d) del=1  ;;
          (D) del=2  ;;
          (h) help=1  ;;
          (L) list=1  ;;
          ([Uzk]) autoopts+=(-$opt)  ;;
          (*) return 1 ;;
     esac
done


# Example taken from 'man getopts(1p)'

aflag=
bflag=
while getopts "ab:" name
do
     case $name in
          a) aflag=1 ;;
          b) bflag=1
             bval="$OPTARG" ;;
          ?) printf "Usage: %s: [-a] [-b value] args\n" $0
             exit 2;;
     esac
done

if [ ! -z "$aflag" ]; then
     printf "Option -a specified\n"
fi

if [ ! -z "$bflag" ]; then
     printf 'Option -b "%s" specified\n' "$bval"
fi

shift $(($OPTIND - 1))
printf "Remaining arguments are: %s\n$*"


