Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: getopts / OPTIND / shift : inconsistent behavior

On Wed, 5 Dec 2007 16:08:26 +1100
"謝步遙 Sie, Bu Yau" <ps@xxxxxxxxxxxx> wrote:
> Hi,
> With zsh 4.3.4 the OPTIND incremental bebavior is inconsistent for options 
> with argument and without argument. For option with argument, OPTIND points 
> to next argument, while for option without argument it points to current 
> argument.
> func() {
> getopts a:b optvar
> shift $(( OPTIND -1 ))
> echo "$OPTIND, $1"
> }
> func -a x y z
> output: 3, y
> func -b x y z
> output: 1, -b
> Is this a bug? There is no consistent way to do "shift" as such.

You can make it consistent by making sure you've got to the end of the
option list before looking at the arguments:

func () {
        while getopts a:b optvar; do :; done
        shift $(( OPTIND -1 ))
        echo "$OPTIND, $1"

This is the way you'd normally use it:  you don't know how many options
there are, if any, until getopts returns 1.

However, it's still a bit fishy.  The internal option index handling logic
has always been a bit curious; I've lost count of the number of bugs we've
had in it.

Peter Stephenson <pws@xxxxxxx>                  Software Engineer
CSR PLC, Churchill House, Cambridge Business Park, Cowley Road
Cambridge, CB4 0WZ, UK                          Tel: +44 (0)1223 692070

Messages sorted by: Reverse Date, Date, Thread, Author