Table of Contents

Bash - getopts - Argument Parser (Builtin command)

About

getopts is a command line utility used to parse positional parameters and short option only.

You may want to use getopt that handle positional parameters as only short/single letter option are supported.

ie d is valid but not de

Example

script.sh -p valuep -d valued -f
while getopts "p:d:" option
do
   case "$option" in
      p)   VARIABLE_FOR_P="${OPTARG}";;
      d)   VARIABLE_FOR_D="${OPTARG}";;
      ?)   echo -e "Usage";;
      *)   echo -e "option ${OPTARG} unknown. Usage:\n" ; exit 1 ;;
   esac
done

where:

if [[ -z "$VARIABLE_FOR_P" ]]; then
	echo "VARIABLE_FOR_P:"
	read VARIABLE_FOR_P
        # Test if null
	[[ "${VARIABLE_FOR_P:?The parameter is null sorry}" ]]
fi

Syntax

getopts optstring name [args]

where:

Process

Each time it is invoked, getopts set the following variable:

At the end of the process, OPTIND is set to the index of the first non-option argument, and name is set to ?.

Return value

When the end of options is encountered, getopts exits with a return value greater than zero.

getopts returns:

Error reporting

If the first character of optstring is a colon, silent error reporting is used.

Silent Error Reporting

If the variable OPTERR is set to:

If a required argument is not found:

No Silent Error Reporting

If a required argument is not found:

If an invalid option is seen:

The option character found is placed in OPTARG and no diagnostic message is printed.