Re: getopts appears to not be shifting $@ when consuming options

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

 



On 29/01/2021 20:15, Harald van Dijk wrote:
I would suggest that if this is changed to conform to POSIX, a non-standard method should remain available to allow shell functions to use getopts internally, including when the getopts loop in the function calls other functions that themselves use getopts, to ensure that any existing scripts broken by the change can be easily updated. One way to achieve that could be to special-case "local OPTIND=1" so that when the function returns, it restores not just the value of OPTIND, but uses that moment to additionally restore the extra internal state.

I have found that "local OPTIND=1" already works that way in bash, restoring upon function return not only the value of OPTIND but also the extra internal extra state. It is designed to work like that, not just a happy accident: it is listed as a new feature of 4.4. Because of that, if something like this is implemented, this would probably be the best syntax to use.

I have also found that this is easy to implement: currently, getoptsreset() just sets the internal state (shellparam.optind and shellparam.optoff) based on the text value of OPTIND. Instead, if:
- var.h defines a new flag to indicate that special hidden data is
  present past the end of OPTIND's text value,
- getopts() builds its own buffer, including the extra hidden data, and
  calls setvareq() directly with that special flag rather than relying
  on setvarint(),
- getoptsreset() checks it to either set the internal state as before
  or restore the internal state, depending on whether that special flag
  is set,
everything just works with no special casing needed in the implementation of the "local" command. The net result is even a small reduction in code size.

I am only posting a description of the changes rather than a patch or a link to a patch because I implemented this in my shell (a fork of dash), not dash itself, and the changes as I implemented them cannot be applied to dash without some modifications.

Cheers,
Harald van Dijk




[Index of Archives]     [LARTC]     [Bugtraq]     [Yosemite Forum]     [Photo]

  Powered by Linux