I'm trying to parse arguments passed to a bash function using getopts inside that function. It works when the function is called for the first time but fails on all subsequent calls.

Here is a simple test case:


function getopt_test {
    while getopts "a:" opt; do
        case $opt in
                PARAMS="${PARAMS} $OPTARG"
    echo "PARAMS => $PARAMS"

getopt_test -a call_1
getopt_test -a call_2

The output of the script is this:

~$ ./tst.sh
PARAMS =>  call_1
PARAMS =>               <--- missing 'call_2'

I guess getopts should somehow be reset before calling it for the second time but I can't really figure out how. Any ideas?


1 Answer 1


The answer is that getopts keeps the pointer in $OPTIND and therefore the trick is to add local OPTIND or OPTIND=1 to the beginning of the getopt_test function.

Thanks to @sivann for providing the link to getopts won't call twice in a row? on StackOverflow

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .