getopts is a built-in command of the shell.
Overview
getopts optstring name [args]
OPTIND,OPTARG,OPTERR
Description
getopts is used by the shell program to analyze positional parameters. optstring contains option characters that need to be recognized. If the character here is followed by a colon, it means that the character option requires a parameter, and its parameters must be separated by spaces. Colons and question marks cannot be used as option characters. Each time getopts is called, it places the next option character in the variable name.
The variable OPTIND is the index of the next positional parameter to be processed, and its initial value is 1. The shell will not automatically reset OPTIND. If you want to analyze the positional parameters again, you need to manually reset OPTIND. When an option requires parameters, getopts places the parameters in the variable OPTARG.
When all the positional parameters are analyzed, getopts exits and returns a value greater than 0. OPTIND becomes the index of the first positional parameter that is not an option, and the name is set to ‘?’. By default, getopts will analyze the incoming positional parameters, but if args has a value, it will only analyze the parameters in args, and args only supports the form of -abc.
If an error is encountered, getopts will print out the error message, but if the first character of the optstring is a colon, or the variable OPTERR is set to 0 (this item just does not print the error message, not after the error Set the value of OPTARG), it will enter the silent mode, and no error message will be printed. There are usually two cases of errors encountered:
1. Invalid options, at this time the name will be set to ‘?’. In silent mode, this invalid option will be placed in OPTARG. Non-silent mode, print error messages, and unset OPTARG.
2. The parameter required by the option is not provided. In the silent mode, the name will be set to ‘:’ and the invalid option will be set to OPTARG. In non-silent mode, the name is set to ‘?’, unset OPTARG and print an error message.
getopts returns true (0) if it encounters an option (whether valid or not). If it encounters the end or produces an error, return false
Example
The example comes from reference [2]
< div class="Highlighter">
#!/bin/sh while getopts :ab:c: OPTION;do case $OPTION in a) echo "get option a" ;; b) echo "get option b and parameter is $OPTARG" ;; c) echo "get option c and parameter is $OPTARG" ;; ?) echo "get a non option $OPTARG and OPTION is $OPTION" ;; esac done