0

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

pah
  • 4,700
  • 6
  • 28
  • 37
  • 1
    why on earth do you use the *index* of the argument? – Karoly Horvath Sep 23 '14 at 16:22
  • do you mean the OPTIND ? ..I thought I could make it work that way, I know its not right though.. – user3632739 Sep 23 '14 at 16:25
  • What @KarolyHorvath is getting at is that `${OPTIND}` is the next index to be looked at, not the value of that argument. You attempted to fix that with `eval` but missed the extra `\$` necessary. But that's not a good way to do that. Use `${@:$OPTIND:1}` instead. Also I think you are shifting too much there. I think you want `shift` to "swallow" one extra argument. Though personally I think this is a poor design. – Etan Reisner Sep 23 '14 at 16:28
  • still new to bash scripting :) I learn to make better design in time. thank you for your time sir. I hope I can make this work – user3632739 Sep 23 '14 at 16:59
  • Your code seems to assume `-a` will be used, in which case it isn't an option. Just use positional parameters: `script.sh power 0000` with `na1=$1; na2=$2` inside. – chepner Sep 23 '14 at 17:48

1 Answers1

0

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

glenn jackman
  • 238,783
  • 38
  • 220
  • 352