Zsh Mailing List Archive
Messages sorted by:
Reverse Date,
Date,
Thread,
Author
OPTIND set incorrectly by getopts for options without arg
- X-seq: zsh-workers 34270
- From: Simon Chiang <simon.a.chiang@xxxxxxxxx>
- To: zsh-workers@xxxxxxx
- Subject: OPTIND set incorrectly by getopts for options without arg
- Date: Tue, 13 Jan 2015 13:38:59 -0700
- Dkim-signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20120113; h=mime-version:date:message-id:subject:from:to:content-type; bh=7/qeQvNMhEgg98CdDc2VQzgrXVA6OsAsUfaQIURahGM=; b=n/JIQ7BWNhiFRIzUD8GjmUlbEXku3rY2X4AdInW9S2i04iqVe2O26h50nFnFJSHosc 5BRnmdtOG9Zc0WSj/Pm6630hiIca8E1FycD3I09wD+aeGMMEoR0khm7uBg5evWzu6pjh oclXWLbnGPpz04wwnBd04pNvSeJsme5o1D1ughPYDhJtzqr7gsGE2K8kGmYeG2zAUUKy K4c7Knqa4T0XwzgMLFLJkB0L9hSKUFYvYean4du9KJlBTB5uRpWtDm4kgnld0XK/tNFY X4WhhcaKIkUNw6gMi47+bOGnlx/nuW16rSu9VAoYu5c4ZSOHdghubPbFte5iFMQ3/EVc XQuw==
- List-help: <mailto:zsh-workers-help@zsh.org>
- List-id: Zsh Workers List <zsh-workers.zsh.org>
- List-post: <mailto:zsh-workers@zsh.org>
- Mailing-list: contact zsh-workers-help@xxxxxxx; run by ezmlm
Back in 2007 there was a question posted to the mailing list regarding
OPTIND and getopts (http://www.zsh.org/mla/users/2007/msg01188.html). To
quote, with some notes and one modifcation:
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() {
OPTIND=1 # reset OPTIND each time in to prevent carryover
getopts a:b optvar
shift $(( OPTIND -1 ))
echo "$OPTIND, $1"
}
func -a x y z
output: 3, y # this is the correct output
func -b x y z
output: 1, -b # this is the questionable output
Is this a bug? There is no consistent way to do "shift" as such.
Turns out according to the POSIX spec this is a bug (
http://pubs.opengroup.org/onlinepubs/000095399/utilities/getopts.html)
When the end of options is encountered, the getopts utility shall exit with
a return value greater than zero; the shell
variable OPTIND shall be set to the index of the first
non-option-argument.... Any of the following shall identify the end of
options: the special option "--", finding an argument that does not begin
with a '-', or encountering an error.
Unless I'm misreading that means that in the first example "y" indicates
the end of options so the correct output is "3, y". In the second example
the "x" indicates the end of options so the correct output is "2, x". For
what it's worth bash and dash set OPTIND in this way.
The original email was regarding zsh 4.3.4. I can confirm this is still
the behavior at zsh 4.3.9.
Simon
Messages sorted by:
Reverse Date,
Date,
Thread,
Author