[bash] getopts not executing when called second time.

Hi,

Unexpectedly, the function below doesn't seem to work
when called a second time. The output shows that when
the function is called the first time, it works as expected
but when it is called a second time, the loop that processes
the options passed to the function, with the while loop,
are completely bypassed.

Thanks in advance.

#!/bin/bash
function fn_check
{
	echo; echo "in check"
	while getopts ":defhrwx" opt; do
	echo "in loop"
	case $opt in
	d)	echo "in d $2";;
	e)	echo "in e";;
	f)	echo "in f";;
	h)	echo "in h";;
	r)	echo "in r";;
	w)	echo "in w";;
	x)	echo "in x";;
	\?)	echo "in ?";;
	esac
	done
}
fn_check -edrw helloworld
fn_check -erwx helloworld

OUTPUT.


in check
in loop
in e
in loop
in d helloworld
in loop
in r
in loop
in w

in check

It keeps track of what argument to read next with OPTIND, which gets set globally. Try:

#!/bin/bash
function fn_check
{
        local OPTIND
        local OPTARG
	echo; echo "in check"
	while getopts ":defhrwx" opt; do
	echo "in loop"
	case $opt in
	d)	echo "in d $2";;
	e)	echo "in e";;
	f)	echo "in f";;
	h)	echo "in h";;
	r)	echo "in r";;
	w)	echo "in w";;
	x)	echo "in x";;
	\?)	echo "in ?";;
	esac
	done
}
fn_check -edrw helloworld
fn_check -erwx helloworld

This should stop it from modifying the global OPTIND value.

You should be able to use ${OPTARG} instead of $2 -- indeed it's preferable to do that instead of hardcoding a parameter as position 2 -- and I'm not sure why that doesn't work.

Thanks for your help, done the trick.

The way I understand it that $2 is not park of the options
string but a separate parameter after the options. As long
as I don't use any OPTARG's with the options it should be
okay. But as soon as I start adding them the positions of
the input parameters could well change.

Thanks again.