A common task in shell scripting is to parse command line arguments to your script. Bash provides the getopts built-in function to do just that. This tutorial explains how to use the getopts built-in function to parse arguments and options to a bash script.

    The getopts function takes three parameters. The first is a so-called _optstring, _a specification of which options are valid, listed as a sequence of letters. For example, the string 'ht' signifies that the options -h and -t are valid.

    The second argument to getopts is a variable that will be populated with the option or argument to be processed next. For example the opt following while-loop, opt will hold the value of the current option that has been parsed by getopts.

    1. while getopts u:d:p:f: opt
    2. do
    3. case "${opt}"
    4. in
    5. \? )
    6. echo "Invalid option: $OPTARG" 1>&2
    7. ;;
    8. : )
    9. echo "Invalid option: $OPTARG requires an argument" 1>&2
    10. ;;
    11. u) USER=${OPTARG};;
    12. d) DATE=${OPTARG};;
    13. p) PRODUCT=${OPTARG};;
    14. f) FORMAT=${OPTARG};;
    15. esac
    16. done

    The colons in the optstring mean that values are required for the corresponding flags. In the above example of u::p:f: , all flags are followed by a colon. This means all flags need a value. If, for example, the d and f flags were not expected to have a value, u:dp:f would be the optstring.

    Options that themselves have arguments are signified with a :. The argument to an option is placed in the variable OPTARG. If no argument is provided getopts will set opt to :. We can recognize this error condition by catching the : case and printing an appropriate error message.

    A colon at the beginning of the optstring (for example, :u:d:p:f: ) has a completely different meaning. It handles flags that are not represented in the optstring. In that case, the value of the opt variable is set to ? and the value of OPTARG is set to the unexpected flag. This behavior displays a suitable error message informing you of the mistake.

    if an invalid option is provided, the option variable is assigned the value ?. You can catch this case and provide an appropriate usage message to the user. Second, this behaviour is only true when you prepend the list of valid options with : to disable the default error handling of invalid options. It is recommended to always disable the default error handling in your scripts.

    The variable OPTIND holds the number of options parsed by the last call to getopts. It is common practice to call the shift command at the end of your processing loop to remove options that have already been handled from $@.

    1. shift $((OPTIND -1))

    Notes: getopts stops parsing options whenever it come across the first non-option argument.

    For more information, please refer to:

    1. How to Pass Arguments to a Bash Script
    2. Parsing bash script options with getopts