How bash getopts knows what arguments the call has
getopts is a bash function, by my understanding, you need to pass
$@ – the whole arguments to
getopts to let the function know what kind of arguments you have in order to proceed, right?
It seems to me that you don’t need it, so how the
getopts get to know what arguments I have in the current scope? Does it have a way to trace the previous call like the other high-level languages do?
while getopts abcde opt; do ˄˄˄˄˄ <-- you only need to pass the argument labels here, how getopts knows what arguments I have case $opt in ... esac done
getopts is a shell built-in, so it can reference
$@ directly. It also sets the shell variables
OPTIND. (Note that inside a function,
getopts will reference that function’s
$@ rather than the global arguments. You should localise
OPTIND if you want a repeatable (odempotent) function call.)
The synopsis (summary) is
getopts optstring name [arg ...]
and the description is such that,
getoptsis used by shell procedures to parse positional parameters.
optstringcontains the option characters to be recognized; if a character is followed by a colon, the option is expected to have an argument, which should be separated from it by white space.
Note that (at least) the
bash documentation (
man bash) also notes,
getoptsnormally parses the positional parameters, but if more arguments are supplied as arg values,
getoptsparses those instead.