[Note that]
getopts is not able to parse GNU-style long options (--myoption) or
XF86-style long options (-myoption)
How it works
- In general you need to call
getopts
several times. - Each time it will use "the next" positional parameter (and a possible argument), if parsable, and provide it to you.
getopts
will not change the positional parameter set — if you want to shift it, you have to do it manually after processing:
shift $((OPTIND-1)) # now do something with $@
Since
getopts
will set an exit status of FALSE when there's nothing left to parse, it's easy to use it in a while-loop:while getopts ...; do ... done
getopts
will parse options and their possible arguments. It will stop parsing on the first non-option argument (a string that doesn't begin with a hyphen (-
) that isn't an argument for any option infront of it). It will also stop parsing when it sees the --
(double-hyphen), which means end of options.[getopts Base Syntax]
The base-syntax for
getopts
is:getopts OPTSTRING VARNAME [ARGS...]where:
OPTSTRING | tells getopts which options to expect and where to expect arguments (see below) |
---|---|
VARNAME | tells getopts which shell-variable to use for option reporting |
ARGS | tells getopts to parse these optional words instead of the positional parameters |
The option-string
- The option-string tells
getopts
which options to expect and which of them must have an argument. - The syntax is very simple — every option character is simply named as is, this example-string would tell
getopts
to look for-f
,-A
and-x
:
getopts fAx VARNAME
- When you want
getopts
to expect an argument for an option, just place a:
(colon) after the proper option flag. - If you want
-A
to expect an argument (i.e. to become-A SOMETHING
) just do:
getopts fA:x VARNAME
- If the very first character of the option-string is a
:
(colon), which normally would be nonsense because there's no option letter preceeding it,getopts
switches to the mode "silent error reporting". In productive scripts, this is usually what you want (handle errors yourself and don't get disturbed by annoying messages).
[Used Variable]
OPTIND
option index, Holds the index to the next argument to be processed.
- This is how
getopts
"remembers" its own status between invocations. Also usefull to shift the positional parameters after processing withgetopts
OPTIND
is initially set to 1, and needs to be re-set to 1 if you want to parse anything again with getopts
OPTARG
option argument, This variable is set to any argument for an option found by
getopts
.- It also contains the option flag of an unknown option.
OPTERR
option error, (Values 0 or 1) Indicates if Bash should display error messages generated by the
getopts
builtin- The value is initialized to 1 on every shell startup - so be sure to always set it to 0 if you don't want to see annoying messages!
http://wiki.bash-hackers.org/howto/getopts_tutorial
沒有留言:
張貼留言