Reputation: 99
I'm supporting below arguments to the script. I want to find out duplicate arguments when its passed and throw an error. Can you please help me.
#! /bin/sh
VCFile=
gCFFile=
PW=xyzzy
while test $# -gt 0
do
option=$(echo $1 | tr a-z A-Z)
case $option in
(-VO) shift
VCfile=$1
;;
(-CON) shift
gCFFile=$1
;;
(-PASSWORD) shift
PW=$1
;;
(*)
print "\nerror -The command line argument $1 is invalid\n"
print "Testscript has aborted.\n"
exit 2
;;
esac
shift
done
./Install.sh -VO abc.txt -CON tt.txt - pass
./Install.sh -VO abc.txt -CON tt.txt -ss
error -The command line argument -ss is invalid
Testscript has aborted.
if running with dup parameters like below
./Install.sh -VO abc.txt -CON tt.txt -CON ta.txt -PASSWORD ABC -PASSWORD non
--doesn't fail , Here I want to throw an error as duplicate options are entered.
Upvotes: 2
Views: 1189
Reputation: 212248
Just check if the value has already been set.
#!/bin/sh
unset VCFile
unset gCFFile
unset PW # set default below
die() { echo "$@"; exit 1; } >&2
while test $# -gt 0
do
option=$(echo $1 | tr a-z A-Z)
case $option in
(-VO) shift
test "${VCFile+set}" = set && die -VO set twice
VCfile=$1
;;
(-CON) shift
test "${gCFFile+set}" = set && die -CON given twice
gCFFile=$1
;;
(-PASSWORD) shift
test "${PW+set}" = set && die -PASSWORD given twice
PW=$1
;;
(*)
die "error -The command line argument $1 is invalid
;;
esac
shift
done
: ${PW=xyzzy} # if -PASSWORD was not given, set a default
Upvotes: 4
Reputation: 1317
You can use below code before while loop.
if [ `echo "$@" | grep -o "\-CON" | wc -l` -gt 0 ] || [ `echo "$@" | grep -o "\-PASSWORD" | wc -l` -gt 0 ] || [ `echo "$@" | grep -o "\-VO" | wc -l` -gt 0 ]
then
echo " Duplicate set of parameter is passed. $# is invalid\n"
echo "Testscript has aborted.\n"
exit 0
fi
OR you can add in case statement to get which parameter is duplicate.
while test $# -gt 0
do
option=$(echo $1 | tr a-z A-Z)
case $option in
(-VO) shift
VCfile=$1
if [ `echo "$@" | grep -o "\-VO" | wc -l` -gt 0 ]
then
echo "Duplicate set of parameter is passed for -VO . Parameters passed are invalid\n"
echo "Testscript has aborted.\n"
exit 0
fi
;;
(-CON) shift
gCFFile=$1;
if [ `echo "$@" | grep -o "\-CON" | wc -l` -gt 0 ]
then
echo "Duplicate set of parameter is passed for -CON . Parameters passed are invalid\n"
echo "Testscript has aborted.\n"
exit 0
fi
;;
(-PASSWORD) shift
PW=$1
if [ `echo "$@" | grep -o "\-PASSWORD" | wc -l` -gt 0 ]
then
echo "Duplicate set of parameter is passed for -PASSWORD . Parameters passed are invalid\n"
echo "Testscript has aborted.\n"
exit 0
fi
;;
(*)
echo "\nerror -The command line argument $1 is invalid\n"
echo "Testscript has aborted.\n"
exit 2
;;
esac
shift
done
let me know if it is working.
Upvotes: 2