Help with "getopts"



I'm writing some shell scripts and trying desperately to understand
"getopts", specifically it's intrinsic variable $OPTIND. The guidance
I've seen so far seems straightforward enough but then just doesn't seem
to jibe with what I actually see when using it. What exactly is $OPTIND
counting? There 'seems' to be a pattern, but every time I think I've
figured out what it is, it 'breaks' for another form of calling a script.
Here's an example ... a simple shell script called 'optscript':

#!/bin/bash
while getopts "abc:def:ghi" flag
do
echo "flag: $flag" "OPTIND: $OPTIND" "OPTARG: $OPTARG"
done

Now the various outputs:

bash>./optscript -abc charlie
flag: a OPTIND: 1 OPTARG:
flag: b OPTIND: 1 OPTARG:
flag: c OPTIND: 3 OPTARG: charlie

bash>./optscript -a -b -c charlie
flag: a OPTIND: 2 OPTARG:
flag: b OPTIND: 3 OPTARG:
flag: c OPTIND: 5 OPTARG: charlie

bash>./optscript -abc charlie -def foxtrot
flag: a OPTIND: 1 OPTARG:
flag: b OPTIND: 1 OPTARG:
flag: c OPTIND: 3 OPTARG: charlie
flag: d OPTIND: 3 OPTARG:
flag: e OPTIND: 3 OPTARG:
flag: f OPTIND: 5 OPTARG: foxtrot

bash>./optscript -a -b -c charlie -d -e -f foxtrot
flag: a OPTIND: 2 OPTARG:
flag: b OPTIND: 3 OPTARG:
flag: c OPTIND: 5 OPTARG: charlie
flag: d OPTIND: 6 OPTARG:
flag: e OPTIND: 7 OPTARG:
flag: f OPTIND: 9 OPTARG: foxtrot

Can anyone tell me what actually causes $OPTIND to increment up one (or
two), and what causes it to stay the same? Thanks ...

Rich Leitner
.



Relevant Pages

  • Re: Help with "getopts"
    ... What exactly is $OPTIND counting? ... flag: a OPTIND: 1 OPTARG: ... flag: c OPTIND: 3 OPTARG: charlie ...
    (alt.os.linux)
  • Re: Help with "getopts"
    ... specifically it's intrinsic variable $OPTIND. ... flag: a OPTIND: 1 OPTARG: ... flag: c OPTIND: 3 OPTARG: charlie ...
    (alt.os.linux)