getopts is a nice way to get simple arguments, rather than having to write your own code to get them.

Let’s start with an example.

while getopts mdvf: arg
   case $name in
   m)  match=1         ;;
   d)  dev=1           ;;
   v)  verbose=1       ;;
   f)  file="$OPTARG"  ;;
   ?)  printf "Usage: %s: [-m] [-dv] [-f file]\n" $0
       exit 1 ;;
   *)  echo "An incorrect argument was specified"  ;;

In here we have set our default values for design and dev. We have then our while getopts argument where we specify the arguments that will be accepted (where you see mdvf:).

The : after the f means that one gets an argument, in this case the file name. The option for the argument is obtained in the $OPTARG variable within the case.

Speaking of which, list all of the arguments in the case section. There are two special arguments:

  • ? means nothing was given. Useful for giving the usage explanation.
  • * means an unknown argument was given.

For more information, see: