Search code examples
bashshellshgetopt

Shell : getopts option with two argument would stop the script


I had make a script called test.sh look like below

while getopts a:b: opt
do
  case $opt in
    a) a1=$OPTARG
       ;;
    b) b1=$OPTARG    
       eval "b2=\${$OPTIND}"
       shift 2;;   

  esac
done

echo $a1;
echo $b1;
echo $b2;

When I try the command below, its work...

test.sh -a 111 -b 222 333

111
222
333

But if I try this one...

test.sh -b 222 333 -a 111 

222
333

It only can display -b argument, -a option and agrument can not work after -b option...

any problem at my script???? thank you :)


Solution

  • Modifying argument indexes with shift 2 does not play along with getopts. Instead you should increment OPTIND by one to get getopts to skip the next argument, e.g something like

    while getopts a:b: opt
    do
            case $opt in
                    a) a1=$OPTARG
                            ;;
                    b) b1=$OPTARG    
                            eval "b2=\${$OPTIND}"
                            OPTIND=`echo $OPTIND + 1 | bc`
                            ;;
            esac
    done
    
    echo $a1;
    echo $b1;
    echo $b2;