Setting OPTIND=1
before invoking getopts
works fine.
The problem is that getopts
relies on OPTIND
to loop through the arguments provided, and after sourcing the script, it will be set to some value greater than 1 by getopts
according to how many arguments you pass. This value gets carried over even after the script ends(because its being sourced). So the next time its sourced, getopts
will pick up from that OPTIND
, rather than starting from 1!
This might cause strange behaviour with other scripts, and I don't know how safe this is. But it works!
For a better workaround, I think what @tripleee suggests looks safe and robust.