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?


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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.