How bash getopts knows what arguments the call has

If 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
Asked By: Till


getopts is a shell built-in, so it can reference $@ directly. It also sets the shell variables OPTARG and 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,

getopts is used by shell procedures to parse positional parameters. optstring contains 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,

getopts normally parses the positional parameters, but if more arguments are supplied as arg values, getopts parses those instead.


Answered By: Chris Davies
Categories: Answers Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.