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

Re: getopts doesn't update OPTIND when called from function



# p.stephenson@xxxxxxxxxxx / 2015-05-28 18:17:40 +0100:
> On Thu, 28 May 2015 18:18:32 +0200
> Martijn Dekker <martijn@xxxxxxxx> wrote:
> > I'm writing a shell function that extends the functionality of the
> > 'getopts' builtin. For that to work, it is necessary to call the
> > 'getopts' builtin from the shell function.
> > 
> > The POSIX standard specifies that OPTIND and OPTARG are global
> > variables, even if the positional parameters are local to the
> > function.[*] This makes it possible to call 'getopts' from a function by
> > simply passing the global positional parameters along by adding "$@".
> > 
> > My problem is that zsh does not update the global OPTIND variable when
> > getopts is called from a function, which defeats my function on zsh. (It
> > does update the global OPTARG variable, though.)
> 
> This is documented behaviour (well, sort of -- the documentation didn't
> say quite what we actually do) so this needs another compatibility fix.
> POSIX_BUILTINS seems appropriate.

thanks for the zshbuiltins(1) clarification.  

i have a problem similar to Martijn's, only there's no function in sight.
this diff shows how zsh (5.0.7, emulate -R sh) differs from other shells,
and the standard IIUC:

   $ getopts abc OPTNAM -a -b -- -c
   $ printf "%s=%s\n" OPTIND "$OPTIND" OPTNAM "$OPTNAM" OPTARG "$OPTARG"
-  OPTIND=2
+  OPTIND=1
   OPTNAM=a
   OPTARG=
   $ getopts abc OPTNAM -a -b -- -c
   $ printf "%s=%s\n" OPTIND "$OPTIND" OPTNAM "$OPTNAM" OPTARG "$OPTARG"
-  OPTIND=3
+  OPTIND=2
   OPTNAM=b
   OPTARG=
   $ getopts abc OPTNAM -a -b -- -c
   [1]
   $ printf "%s=%s\n" OPTIND "$OPTIND" OPTNAM "$OPTNAM" OPTARG "$OPTARG"
   OPTIND=4
-  OPTNAM=?
+  OPTNAM=b
   OPTARG=

it would be nice to have zsh aligned with other shells, at least under
posix_builtins or 'emulate sh'.

-- 
roman



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