GETOPTS(1P)
๐ธ GETOPTS(1P) โ the POSIX Programmer's Manual, but make it make sense ๐ธ
okay bestie, quick heads up before we dive in: this page lives in the POSIX Programmer's Manual. The Linux implementation of this interface may differ (so go peek at the corresponding Linux manual page for the tea on Linux behavior), or honestly the interface might just not be implemented on Linux at all. ๐
โจ NAME โจ
getopts โ parse utility options. that's it, that's the job. ๐
โจ SYNOPSIS โจ
getopts optstring name [arg...]
โจ DESCRIPTION โจ
So the getopts utility shall retrieve options and option-arguments from a list of parameters. It shall support the Utility Syntax Guidelines 3 to 10, inclusive, described in the Base Definitions volume of POSIX.1โ2017, Section 12.2, Utility Syntax Guidelines. iconic behavior tbh. ๐
Every single time it is invoked, getopts shall place the value of the next option in the shell variable specified by the name operand, and the index of the next argument to be processed in the shell variable OPTIND. And whenever the shell is invoked, OPTIND shall be initialized to 1. every. single. time. no cap.
When the option requires an option-argument, getopts shall place it in the shell variable OPTARG. If no option was found, or if the option that was found does not have an option-argument, OPTARG shall be unset. gone. unset. ๐
Now, the messy part โ if an option character not contained in the optstring operand is found where an option character is expected, the shell variable specified by name shall be set to the <question-mark> ('?') character. In this case:
- if the first character in
optstringis a<colon>(':'), the shell variableOPTARGshall be set to the option character found, but no output shall be written to standard error ๐คซ - otherwise, the shell variable
OPTARGshall be unset and a diagnostic message shall be written to standard error ๐ข
This condition shall be considered to be an error detected in the way arguments were presented to the invoking application, but shall not be an error in getopts processing. so like, not getopts's fault, it's the args' fault. ๐ซถ
If an option-argument is missing:
- If the first character of
optstringis a<colon>, the shell variable specified bynameshall be set to the<colon>character and the shell variableOPTARGshall be set to the option character found. - Otherwise, the shell variable specified by
nameshall be set to the<question-mark>character, the shell variableOPTARGshall be unset, and a diagnostic message shall be written to standard error. This condition shall be considered to be an error detected in the way arguments were presented to the invoking application, but shall not be an error ingetoptsprocessing; a diagnostic message shall be written as stated, but the exit status shall be zero. yes, zero. plot twist. ๐ญ
When the end of options is encountered, the getopts utility shall exit with a return value greater than zero; the shell variable OPTIND shall be set to the index of the first operand, or the value "$#"+1 if there are no operands; the name variable shall be set to the <question-mark> character. Any of the following shall identify the end of options:
- the first
"--"argument that is not an option-argument, - finding an argument that is not an option-argument and does not begin with a
'-', - or encountering an error.
The shell variables OPTIND and OPTARG shall be local to the caller of getopts and shall not be exported by default. they're yours, keep them. ๐
The shell variable specified by the name operand, OPTIND, and OPTARG shall affect the current shell execution environment; see Section 2.12, Shell Execution Environment.
If the application sets OPTIND to the value 1, a new set of parameters can be used: either the current positional parameters or new arg values. Any other attempt to invoke getopts multiple times in a single shell execution environment with parameters (positional parameters or arg operands) that are not the same in all invocations, or with an OPTIND value modified to be a value other than 1, produces unspecified results.
๐จ bestie this is the danger zone. same params every time, or resetOPTINDto1. anything else and the results are unspecified. that means nobody promised you anything. not even a little bit. ๐
โจ OPTIONS โจ
None. literally none. getopts doesn't take options, it is the options. main character energy. โจ
โจ OPERANDS โจ
The following operands shall be supported:
optstringโ A string containing the option characters recognized by the utility invokinggetopts. If a character is followed by a<colon>, the option shall be expected to have an argument, which should be supplied as a separate argument. Applications should specify an option character and its option-argument as separate arguments, butgetoptsshall interpret the characters following an option character requiring arguments as an argument whether or not this is done. An explicit null option-argument need not be recognized if it is not supplied as a separate argument whengetoptsis invoked. (See also thegetopt()function defined in the System Interfaces volume of POSIX.1โ2017.) The characters<question-mark>and<colon>shall not be used as option characters by an application. The use of other option characters that are not alphanumeric produces unspecified results. If the option-argument is not supplied as a separate argument from the option character, the value inOPTARGshall be stripped of the option character and the'-'. The first character inoptstringdetermines howgetoptsbehaves if an option character is not known or an option-argument is missing.nameโ The name of a shell variable that shall be set by thegetoptsutility to the option character that was found.
The getopts utility by default shall parse positional parameters passed to the invoking shell procedure. If args are given, they shall be parsed instead of the positional parameters. your call, bestie. ๐ซ
โจ STDIN โจ
Not used. doesn't want it, doesn't need it. ๐ โ๏ธ
โจ INPUT FILES โจ
None. zero. nada. ๐
โจ ENVIRONMENT VARIABLES โจ
The following environment variables shall affect the execution of getopts:
LANGโ Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of POSIX.1โ2017, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.)LC_ALLโ If set to a non-empty string value, override the values of all the other internationalization variables.LC_CTYPEโ Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments and input files).LC_MESSAGESโ Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.NLSPATHโ Determine the location of message catalogs for the processing ofLC_MESSAGES.OPTINDโ This variable shall be used by thegetoptsutility as the index of the next argument to be processed.
โจ ASYNCHRONOUS EVENTS โจ
Default. nothing fancy. ๐ฆ
โจ STDOUT โจ
Not used. the vibes go elsewhere. โจ
โจ STDERR โจ
Whenever an error is detected and the first character in the optstring operand is not a <colon> (':'), a diagnostic message shall be written to standard error with the following information in an unspecified format:
- The invoking program name shall be identified in the message. The invoking program name shall be the value of the shell special parameter
0(see Section 2.5.2, Special Parameters) at the time thegetoptsutility is invoked. A name equivalent to:
basename "$0"
may be used.
- If an option is found that was not specified in
optstring, this error is identified and the invalid option character shall be identified in the message. - If an option requiring an option-argument is found, but an option-argument is not found, this error shall be identified and the invalid option character shall be identified in the message.
โจ OUTPUT FILES โจ
None. ๐
โจ EXTENDED DESCRIPTION โจ
None. we keep it simple around here. ๐ธ
โจ EXIT STATUS โจ
The following exit values shall be returned:
0โ An option, specified or unspecified byoptstring, was found.>0โ The end of options was encountered or an error occurred.
โจ CONSEQUENCES OF ERRORS โจ
Default.
The following sections are informative.
โจ APPLICATION USAGE โจ
Since getopts affects the current shell execution environment, it is generally provided as a shell regular built-in. If it is called in a subshell or separate utility execution environment, such as one of the following:
(getopts abc value "$@")
nohup getopts ...
find . -exec getopts ... \;
it does not affect the shell variables in the caller's environment. so cute, so contained, so ineffective. ๐ญ
Note that shell functions share OPTIND with the calling shell even though the positional parameters are changed. If the calling shell and any of its functions uses getopts to parse arguments, the results are unspecified.
๐จ okay this one gets people every time: shell functions and the calling shell are sharing the sameOPTIND. if both of y'all are runninggetopts, the results are unspecified. don't do it. i'm begging. ๐
โจ EXAMPLES โจ
The following example script parses and displays its arguments:
aflag=
bflag=
while getopts ab: name
do
case $name in
a) aflag=1;;
b) bflag=1
bval="$OPTARG";;
?) printf "Usage: %s: [-a] [-b value] args\n" $0
exit 2;;
esac
done
if [ ! -z "$aflag" ]; then
printf "Option -a specified\n"
fi
if [ ! -z "$bflag" ]; then
printf 'Option -b "%s" specified\n' "$bval"
fi
shift $(($OPTIND - 1))
printf "Remaining arguments are: %s\n$*"
look at that. ate. ๐
๐ RATIONALE (aka why is it Like This)
Okay bestie, gather round, because there's lore. ๐ซถ
The getopts utility was chosen in preference to the System V getopt utility because getopts handles option-arguments containing <blank> characters. Yeah. That's the whole reason. Spaces in your option args, handled. Iconic behavior, honestly. โจ
The OPTARG variable is not mentioned in the ENVIRONMENT VARIABLES section because it does not affect the execution of getopts; it is one of the few ``output-only'' variables used by the standard utilities. So it's not an input, it's just the utility handing you a little gift on the way out. ๐
The <colon> is not allowed as an option character because that is not historical behavior, and it violates the Utility Syntax Guidelines. No cap. But the <colon> is now specified to behave as in the KornShell version of the getopts utility; when used as the first character in the optstring operand, it disables diagnostics concerning missing option-arguments and unexpected option characters. And that replaces the use of the OPTERR variable that was specified in an early proposal. So long, OPTERR. ๐
Now, the drama section. ๐ The formats of the diagnostic messages produced by the getopts utility and the getopt() function are not fully specified because implementations with superior (``friendlier'') formats objected to the formats used by some historical implementations. The standard developers considered it important that the information in the messages used be uniform between getopts and getopt(). Exact duplication of the messages might not be possible, particularly if a utility is built on another system that has a different getopt() function, but the messages must have specific information included so that the program name, invalid option character, and type of error can be distinguished by a user. Like, the vibe of the message can differ, but the facts gotta be there. Periodt. ๐
Only a rare application program intercepts a getopts standard error message and wants to parse it. Therefore, implementations are free to choose the most usable messages they can devise. The following formats are used by many historical implementations:
"%s: illegal option -- %c\n", <program name>, <option character>
"%s: option requires an argument -- %c\n", <program name>, \
<option character>
Historical shells with built-in versions of getopt() or getopts have used different formats, frequently not even indicating the option character found in error. ๐ญ The disrespect of not even naming the offending option. Wild.
๐ฎ FUTURE DIRECTIONS
None.
That's it. That's the whole section. Nothing is coming. The future is empty, bestie. Main character energy of a section that simply refuses to elaborate. ๐ฆ
๐ SEE ALSO
- Section 2.5.2, Special Parameters
- The Base Definitions volume of POSIX.1โ2017, Chapter 8, Environment Variables, Section 12.2, Utility Syntax Guidelines
- The System Interfaces volume of POSIX.1โ2017,
getopt()
Go read those, iykyk. ๐โจ
ยฉ๏ธ COPYRIGHT
Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1-2017, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 7, 2018 Edition, Copyright (C) 2018 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .
Any typographical or formatting errors that appear in this page are most likely to have been introduced during the conversion of the source files to man page format. To report such errors, see https://www.kernel.org/doc/man-pages/reporting_bugs.html .
Fr fr, if you spot a typo, it's a conversion glitch, not a standard glitch. Report it at the link above and be the hero of the man page. ๐ซก๐
And that's a wrap on GETOPTS(1P), babes! This little gem came to us from IEEE/The Open Group, 2017 โ shoutout to them for the lore, the copyright, and the iconic footer text. ๐ Go write some shell scripts and parse those options like the queen you are. Slay. ๐๐ธ
๐ฆ where this page comes from
- alpine 3.22: man-pages-posix 2017a-r0 ยท custom
- alpine 3.23: man-pages-posix 2017a-r0 ยท custom
- alpine 3.24: man-pages-posix 2017a-r0 ยท custom
- arch rolling: man-pages 6.19-1
- arch rolling: man-pages 6.20-1 ยท BSD-2-Clause AND BSD-3-Clause AND BSD-4.3TAHOE AND BSD-4-Clause-UC AND GPL-1.0-or-later AND GPL-2.0-only AND GPL-2.0-or-later AND GPL-3.0-or-later AND LGPL-3.0-linking-exception AND LGPL-3.0-or-later AND LicenseRef-Public-Domain AND LicenseRef-UltraPermissive AND Linux-man-pages-1-para AND Linux-man-pages-copyleft AND Linux-man-pages-copyleft-2-para AND Linux-man-pages-copyleft-var AND MIT AND Spencer-94
- nixpkgs unstable: man-pages-posix 2017a
- opensuse-leap 16.0: man-pages-posix 2017a-160000.4.1 ยท SUSE-IEEE
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms