0

This is my first attempt using getopts, and so far it hasn't been working for me. The code in my script is:

while getopts "s:" opt; do
 case $opt in
    s) subj=$OPTARG;;
    \?) echo "Incorrect usage";;
 esac
done

echo ""
echo $subj

When I try to run to script like this:

myScript.sh -s 100

I want it to echo the subject id number I've specified. So far though it just gives me a blank statement.

codeforester
  • 39,467
  • 16
  • 112
  • 140
djl
  • 267
  • 1
  • 3
  • 13
  • Cannot reproduce, outputs 100 for me. Are you sure you're running the correct script? `myScript.sh` requires the script to be executable and in a directory in your `PATH`, and the current working directory typically is *not* in the `PATH` for security reasons. – chepner Mar 13 '18 at 17:57
  • Ah, I see. I think my issue was also that I was doing source myScript.sh -s 100. When I just type myScript.sh -s 100 then it works. I'm not sure why it's an issue when I type "source" – djl Mar 13 '18 at 18:08
  • Ah, I bet it works the *first* time you use `source myScript.sh -s 100` in a shell, though, doesn't it? The counter `getopts` uses to know which argument is next doesn't get reset between successive sources, so `getopts` simply doesn't see any arguments to parse. Explicitly setting `OPTIND=1` before you use `source` again should give you the expected behavior. – chepner Mar 13 '18 at 18:14

1 Answers1

2

getopts uses the current value of OPTIND to know which argument to look at next. If you are using source to run your script, though, OPTIND never gets reset between calls. You probably added subj after the first run, so that its value wasn't set the first time you sourced the script. Explicitly setting OPTIND=1 would fix it.

$ source myScript.sh -s 100

100
$ unset subj; source myScript.sh -s 100


$ OPTIND=1
$ source myScript.sh -s 100

100
chepner
  • 497,756
  • 71
  • 530
  • 681