getopts not updating from subroutine.

So, I'm running a script with a couple of subroutines, one of which takes arguments using getopts. The first time i call the subroutine everything works as expected, the second time I call it none of the arguments change. Here's a small section of code that shows this behavior.

#!/bin/sh
#Testing getopts

Sbrt()
{
while getopts ":a:b:" opt; do
    case $opt in
    a ) aarg="$OPTARG";;
    b ) barg="$OPTARG";;
    \?) echo "usage" ;;
    esac
done
shift $(($OPTIND - 1))

echo $aarg $barg
}

Sbrt -a A1 -b B1
Sbrt -a A2 -b B2

Output:

A1 B1
A1 B1

So how can I call the subroutine again and have it update the arguments (aside from making the subroutine a separate script, of course). I searched, if anyone knows of any threads pertaining to this let me know and i'll clear this out of here.

I don't know if this is the "proper" way to do things but it works. Change the line:

shift $(($OPTIND - 1))

to:

OPTIND=1

Thanks,

I thought that line might be trouble but didn't know much about what it did so I left it be.

Ha. Truth be told, I don't know what it does (or is supposed to do) either. I know what shift does. I know what OPTIND is. Together it's weird. OPTIND starts at 1 and at the end of reading your args is 5. Shift will shift positional parameters by 1 (or by n if 'shift n') so, what I see is "shift positional parameters forward 5-1 (or 4).

On the other hand. I've seen that used before just never had to deal with it directly so it must be useful. Maybe someone else will shed some light.

Glad I could help