I have a case where the script has to run in two modes as options and based on the mode, script excepts optional and mandatory arguments.
script.sh -a -f <value1> -d <value2> -h <value3>
script.sh -b -i <value4>
a and b are the modes of the script execution.
value2, value3 are optional.
I just know the basic usage of getopts. But can someone help me implementing the case in getops?
Thanks in advance!
vbe
September 8, 2014, 10:35am
2
Maybe should you explain us how you see your getopts stanza...
what have you done so far?
This is what i tried. Mainly I'm facing issue while applying mutually exclusive conditions of the options. Like either a or b should be passed, but not both and likewise optional arguments as well.
while getopts :abf:d:h:i: mode
do
case $mode in
a)adhoc=1;;
b)batch=1;;
f)fn=$OPTARG;;
d)del=$OPTARG;;
h)hd=$OPTARG;;
i)id=$OPTARG;;
*)echo "Invalid arg";;
esac done
if [[ ! -z $adhoc ]]
then
echo "Adhoc processing"
echo "fn: " $fn
echo "del: " $del
echo "hd: " $hd
fi
if [[ ! -z $batch ]]
then
echo "Batch processing"
echo "id: " $id
fi
Ditto
September 8, 2014, 12:57pm
4
ksailesh1:
This is what i tried. Mainly I'm facing issue while applying mutually exclusive conditions of the options. Like either a or b should be passed, but not both and likewise optional arguments as well.
while getopts :abf:d:h:i: mode
do
case $mode in
a)adhoc=1;;
b)batch=1;;
f)fn=$OPTARG;;
d)del=$OPTARG;;
h)hd=$OPTARG;;
i)id=$OPTARG;;
*)echo "Invalid arg";;
esac done
if [[ ! -z $adhoc ]]
then
echo "Adhoc processing"
echo "fn: " $fn
echo "del: " $del
echo "hd: " $hd
fi
if [[ ! -z $batch ]]
then
echo "Batch processing"
echo "id: " $id
fi
Personally, I'd probably just do validation on all the arguments after you finish grabbing them with getopts:
So just add this after your existing getopts case (and prior to your other ifs):
if [[ $adhoc -eq 1 && $batch -eq 1 ]]
then
echo "Cannot specify both adhoc and batch."
exit 1
fi
(for example) ...
ditto:
Personally, I'd probably just do validation on all the arguments after you finish grabbing them with getopts:
So just add this after your existing getopts case (and prior to your other ifs):
if [[ $adhoc -eq 1 && $batch -eq 1 ]]
then
echo "Cannot specify both adhoc and batch."
exit 1
fi
(for example) ...
That covers the case where both of the exclusive options are present, but doesn't notice if neither -a
nor -b
was given. Perhaps adding:
adhoc=0
batch=0
before the getopts
loop and:
if [ $((adhoc + batch)) -ne 1 ]
then echo "Exactly one of -a and -b must be specified." >&2
exit 1
fi
after the loop would be better.