I have this shell script that is supposed to accept two optional parameters start
and end
from command line:
function foo {
# -s : start
# -e : end
while getopts 's:e:' arg
do
case ${arg} in
s) start=${OPTARG};;
e) end=${OPTARG};;
*) return 1 # illegal option
esac
done
echo "start, end:"
echo $start, $end
unset start
unset end
}
I get random results from the runs. Here is a list of runs (in chronological order), and their outputs:
1.
$ foo
start, end:
,
2.
$ foo -s 2011
start, end:
2011,
3.
$ foo -e 2015
start, end:
,
4.
$ foo -s 2011 -e 2016
start, end:
, 2016
5.
$ foo -s 2011 -e 2016
start, end:
,
6.
$ foo
start, end:
,
7.
$ foo -s 2011 -e 2016
start, end:
2011, 2016
8.
$ foo -s 2011 -e 2016
start, end:
,
Please help. The requirement is as simple as the first two lines of this post. Any alternative method works too, but I would love to know what I'm doing wrong here. TIA.
Your function sets global variable
OPTIND
due to invocation of getopts. You can prevent this by addinglocal OPTIND
at the beginning of your function (you might want to do that for variablesend
andstart
as well).