Op 20-06-18 om 17:45 schreef Ilkka Virta:
$ for sh in dash 'busybox sh' bash ksh93 zsh ; do printf "%-10s: "
"$sh"; $sh -c 'while getopts abcd opt; do printf "$OPTIND "; done;
printf "$OPTIND "; shift $(($OPTIND - 1)); echo "$1" ' sh -a -bcd
hello; done
dash : 2 3 3 3 3 hello
busybox sh: 2 3 3 3 3 hello
bash : 2 2 2 3 3 hello
ksh93 : 2 2 2 3 3 hello
zsh : 1 2 2 2 3 hello
yash has interesting behaviour here. While other shells use an extra
internal (i.e. not exposed to the shell language) state variable to keep
track of parsing multiple options combined in a single argument, yash
just adds that extra state value to OPTIND.
yash : 1:2 2:2 2:3 2:4 3 hello
Which demonstrates quite well that the value of OPTIND in the middle of
processing really should be considered unspecified, and that only the
initial value (1) and the final value can be relied upon.
Relevant POSIX text:
http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html#tag_20_54
| 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.
- M.