My requirement is that I want to pass similar argument to a shell script and process it in the script. Something like below:
myScript.sh -c COMPONENT1 -c COMPONENT2 -a APP
Note: -c option can be specified multiple times and -a is optional parameter
I know this can be achieved using parser.add_option in Perl. But can be this be done in Shell?
getopts
might help you. Have a look at this sample script:
m@home$cat test.sh
#! /bin/bash
#An array to hold the values passed using -c option
declare -a c_arr
#The count of -c options
c_count=0
#Go through all the optins passed
while getopts ":c:a:" o
do
case "${o}" in
c)
c_arr[$c_count]=${OPTARG}
let c_count=$c_count+1
;;
a)
a=${OPTARG}
;;
*)
echo "Wrong usage"
exit 1
;;
esac
done
if [ $c_count -eq 0 ]
then
echo "option -c is mandatory"
exit 1
fi
let i=$c_count-1
while [ $i -ge 0 ]
do
echo "Got value for c option: ${c_arr[$i]}"
let i=$i-1
done
if [ ! -z $a ]
then
echo "Got value for a option: $a"
fi
And the output
m@home$./test.sh -c C1 -c C2 -a A
Got value for c option: C2
Got value for c option: C1
Got value for a option: A
1 Like
Thanks a lot chacko193 !!