getopts won't call twice in a row?
Just add:
local OPTIND
at the top of your function.
To explain why Dennis's answer works, see the bash
man page (search for getopts
):
OPTIND is initialized to 1 each time the shell or a shell script is invoked.
The shell does not reset OPTIND automatically; it must be manually reset between multiple calls to getopts within the same shell invocation if a new set of parameters is to be used.
This is how getopts
can process multiple options.
If getopts
didn't maintain global state in the OPTIND
variable, each call to getopts
in your while
loop would keep processing $1
, and never advance to the next argument.