9.3.15 getopts command (parses option arguments)
Syntax
getopts optstr name [args ...]
Description
This command parses specified option arguments.
Arguments
- optstr
Specifies a string of valid option characters. When a character is followed by a colon (:), it indicates that the option has an associated value.
You specify a string of option characters that are valid as arguments for specification on the command line or in args. For example, specify ab for the options -a and -b. Multibyte characters cannot be used.
When a character specified in this argument is determined to be a valid option, the matching option is set in the variable whose name is specified in name. When a specified character is not found to be a valid option, ? is set in the variable whose name is specified in name.
If an option has a value, specify a colon (:) after the option character, in which case the value associated with the matching option will be set in the OPTARG shell variable. The getopts command parses the options starting at the argument index (which begins with 1) specified in the OPTIND shell variable. For example, if -a 10 is specified in args, the position of -a will be index 1.
- name
Specifies a variable in which the option characters matched by the getopts command are to be set.
- args
Specifies arguments that are to be parsed. When this option is omitted, getopts parses only the command-line options.
Return codes
Return code |
Meaning |
---|---|
0 |
Normal termination |
1 |
|
Notes
Even if the command syntax of this regular built-in command is invalid, it does not exit the shell that is executing the command.
When executing the getopts command in a separate process, such as the & operator and a command substitution, also see the notes provided in 5.1.7 Execution as a separate process.
Example
Parse -b as a valid option.
Contents of the job definition script
getopts b: name -b 10 echo $name
Contents of the STDOUT file of the execution job
******** JOB SCOPE STDOUT ******** b