bug-bash
[Top][All Lists]
Advanced

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

Re: equivalent of Linux readlink -f in pure bash?


From: Clark J. Wang
Subject: Re: equivalent of Linux readlink -f in pure bash?
Date: Thu, 11 Aug 2011 14:55:22 +0800

On Wed, Aug 10, 2011 at 6:00 PM, Bernd Eggink <monoped@sudrala.de> wrote:

> On 09.08.2011 15:50, Steven W. Orr wrote:
>
>  *) You reset OPTIND to 1 but you didn't declare it local. This will
>> cause any caller of getlink which uses getopts to reset its variable
>> to 1. (I mention this because it cost me a couple of hours a while
>> back.)
>>
>
> The reason I didn't declare OPTIND local is that OPTIND is handled
> specially by the shell; there is always exactly _one_ instance of this
> variable. In other words, OPTIND is always global, even if declared local
> (which is indeed pretty weird). Try this:
>
>
I always declare OPTIND as local. I didn't know it does not work at all.
Bug?


> ------------------------------**-
> function f
> {
>    local OPTIND=1
>
>    echo "\$1=$1"
> }
>
> while getopts "abcdefg" opt
> do
>    echo "opt=$opt"
>    f $opt
> done
> ------------------------------**--
>
> Calling the sript like this works fine:
>        script -a -b -c
>
> But calling it like this leads to an endless loop:
>        script -abc
>
> One could of course save and restore the original:
>
> ------------------------------**-
> function f
> {
>    local oldind=$OPTIND
>
>    OPTIND=1
>    echo "\$1=$1"
>    OPTIND=$oldind
> }
> ------------------------------**-
>
> However, this also loops endlessly. The reason is most likely that bash
> maintains an additional internal variable holding the index of the current
> character, relative to the current word. While this variable is not directly
> accessible by the user, it is set to 0 whenever OPTIND is assigned a value.
>
> So the only safe way is to _never_ use getopts within another getopts
> block, but always wait until the first one has finished.
>


reply via email to

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