How to parse arguments in bash

Syntax: getopts optstring varname [arg ...]

optstring = a string with the list of arguments, varname — the name of the variable the option will be written to, arg — the list of arguments (defaults to $@).

The string format is a list of characters (‘:’ and ‘?’ are not allowed); if a character is followed by ‘:’, then the option must be followed by an argument.

If the string starts with ‘:’, bash will not print parsing errors on its own (see the example script).

OPTIND = the index of the argument; at the start of the script it is 1, and it is incremented on each successful call. It can be set to another value. It is not reset automatically!

OPTARG = the option’s argument, if any (for example -n 1 -> OPTARG=1).

If getopts encounters an invalid option, it sets varname to ‘?’ and puts the option’s value into OPTARG. If the option is valid but the argument is missing, then varname is set to ‘:’ and OPTARG also holds the option’s value.

Example (stolen from https://www.golinuxcloud.com/bash-getopts/ and modified):

#!/bin/bash

function usage {
        echo "Usage: $(basename $0) [-h] [-n NUM]"
}

# list of arguments expected in the input
optstring=":hn:"

while getopts ${optstring} arg; do
  case ${arg} in
    h)
      echo "showing usage!"
      usage
      ;;
    n)
      echo "-n arg is ${OPTARG}"
      ;;
    :)
      echo "$0: Must supply an argument to -$OPTARG." >&2
      exit 1
      ;;
    ?)
      echo "Invalid option: -${OPTARG}."
      exit 2
      ;;
  esac
done
echo $OPTIND