Search code examples
bashgetopts

getops 1 option to receive 2 arguments


I've searched around found out that getops receives zero or one argument only, But I really need to make this work,

I need to make my script run like this: ./script.sh -a string integer

What it does is write the string and integer into a text file.

I tried this code:

 while getopts a:d opt
 do
 case "$opt" in

 a) na1=$OPTARG
    eval "na2=${OPTIND}"
    shift 2
    ;;

 d) ./viewS.sh;;

 esac
 done

if [ $isdef -eq 0 ]
then
    echo "$na1;$na2" >>PBDB.txt

fi

I can write the string part into the text file but the integer just keeps resulting to "3".

sample: ./script.sh -a power 0000

result inside textfile: power;3

any suggestions?

just recently started learning bash scripting


Solution

  • Assuming your tag is accurate (you're not using /bin/sh), change

    eval "na2=${OPTIND}"
    

    to use an "indirect variable"

    na2=${!OPTIND}
    

    With eval, you'd need eval na2=\$$OPTIND but that's much uglier