3

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:

#!/bin/bash

function getopt_test {
    PARAMS=""
    while getopts "a:" opt; do
        case $opt in
            a)
                PARAMS="${PARAMS} $OPTARG"
                ;;
        esac
    done
    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?

2

1 Answer 1

4

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 .