Hi all,

I'm unsure of what `getopts` should do to `OPTIND` when working with
grouped options.

Consider the following script:

```sh
getopts "ab:c:" opt -ab hi -c hello ; printf "OPTIND=%1s opt=%1s OPTARG=%-5s 
?=%d\n" "$OPTIND" "$opt" "$OPTARG" "$?"
getopts "ab:c:" opt -ab hi -c hello ; printf "OPTIND=%1s opt=%1s OPTARG=%-5s 
?=%d\n" "$OPTIND" "$opt" "$OPTARG" "$?"
getopts "ab:c:" opt -ab hi -c hello ; printf "OPTIND=%1s opt=%1s OPTARG=%-5s 
?=%d\n" "$OPTIND" "$opt" "$OPTARG" "$?"
getopts "ab:c:" opt -ab hi -c hello ; printf "OPTIND=%1s opt=%1s OPTARG=%-5s 
?=%d\n" "$OPTIND" "$opt" "$OPTARG" "$?"
```

Existing shells seem to exhibit one of two behaviors: early and late
incrementing. In the early-incrementing group, dash and mksh (and
smoosh) all set OPTIND to 2, then 3, then 5. In the late-incrementing
group, bash, zsh, and ksh set OPTIND to 1, then 3, then 5. yash seems to
be non-conformant, setting OPTIND first to 1:2, then 3, then 5.

The core issue is that the `getopts` specification (in particular, the
mandate to allow grouped options per Utility SYntax Guideline 5) can
only be met by tracking extra state---the offset into the current
option. yash reveals this state, but most shells seem to keep it hidden.

My question is: are both of these behaviors (the early-incrementing
OPTIND=2 at first and the late-incrementing OPTIND=1 at first) allowed?
One might read "the `getopts` utility shall place ... the index of the
next argument to be processed in the shell variable `OPTIND`" and assume
that late-incrementing is the right choice (since we're still processing
the first argument after processing `-a`), but it's not 100% clear to me
that's the right interpretation.

Cheers,
Michael

Reply via email to