This seems like a weird question to have, but I need to write a simple bash script that takes two arguments from the command line. The script looks like this:
#!/bin/bash
while getopts a:b: flag; do
case "${flag}" in
a) optionA="${OPTARG}";;
b) optionB="${OPTARG}";;
esac
done
echo $optionA
echo $optionB
When I run . script.sh -a optionA -b optionB
it works exactly as expected and echos the two inputs. The issue is if I run the exact same script again, the arguments are not echoed and I just see two blank lines. Only the first time running it produces the correct behavior. If I close the terminal session and try again it works, but I'd like to be able to run it several times in a row.
I was thinking the issue had something to do with the variables remaining and then being overwritten by the next run so I tried something like unset optionA
, but it did not help.
I apologize if this is a simple question, but I could not seem to find an answer anywhere else and I would much appreciate any help. Thanks!
EDIT: The simple solution is that I was sourcing the script when I could have been running it. Using bash test.sh -a optionA -b optionB
works just fine.
EDIT 2: If there is a need to source instead of run, the answer Charles gave also works; use unset OPTIND
after each run.