I am trying to run the following script using getopts to parse the options but it does not seem to work:
#!/bin/bash
set -x
echo $@
while getopts "rf" opt
do
case "${opt}" in
r)
ropt=${OPTARG}
;;
f)
fopt=${OPTARG}
;;
esac
done
shift $((OPTIND -1))
echo $fopt $ropt
The output I get is:
$ ./myscript.sh -f opt2 -r opt1
+ echo -f opt2 -r opt1
-f opt2 -r opt1
+ getopts rf opt
+ case "${opt}" in
+ fopt=
+ getopts rf opt
+ shift 1
+ echo
+ set +x
Do you have any ideas on what am I doing wrong?
$((OPTIND -1))? Isn't the result of an arithmetic expression always a number? – user000001 Dec 12 '18 at 17:43$IFSmay include digits. which means that the number could be split into multiple words/numbers. Test withn=123; ( IFS=13; echo $n ). – Kusalananda Dec 12 '18 at 17:45IFSfor each new shell invocation.dashdoes not, so potentially one couldexport IFS=0123456789before running a/bin/shshell script on Unices whereshisdashjust to see in what way it breaks. – Kusalananda Dec 12 '18 at 17:48IFS=-to split something on dashes, and then not resetting it, causing the leading minus sign to be lost. Arguably the bug would be caused by not resetting the original value ofIFSand not by the lack of quotes, but I guess it never hurts to program defensively. – user000001 Dec 12 '18 at 18:02