[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: $OPTIND varibale value is different from sh

From: Ilkka Virta
Subject: Re: $OPTIND varibale value is different from sh
Date: Wed, 20 Jun 2018 19:45:52 +0300
User-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:52.0) Gecko/20100101 Thunderbird/52.8.0

On 20.6. 15:39, Greg Wooledge wrote:
On Wed, Jun 20, 2018 at 05:16:48PM +0900, Hyunho Cho wrote:
set -- -a -bc hello world
getopts abc opt "$@"
getopts abc opt "$@"          # bash  = b, 2                  <------ different from 
echo $opt, $OPTIND            # sh      = b, 3

Since POSIX doesn't say anything about what OPTIND should contain
when you're in the middle of processing an argument with multiple
concatenated options inside it, I'd say that this falls into the
realm of "unspecified behavior", and shells can do anything they
want.  So, not a bug in bash.  Or in dash.  Or in ksh, which by the
way does the same thing as bash.

Even worse, OPTIND doesn't contain all the necessary information. It just points at an argument, but doesn't tell what character within it is being processed (next). Resetting OPTIND to 1 is valid, so assigning to it has to clear that hidden information, so a simple OPTIND=$OPTIND can have some curious effects...

I tested a couple of shells out of curiosity. Zsh in particular has a yet another set of values it returns in OPTIND during the loop. Though in the end, the final value is correct in all shells I tried:

$ 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

Ilkka Virta / address@hidden

reply via email to

[Prev in Thread] Current Thread [Next in Thread]