我支持以下脚本参数。我希望在传递并发出错误时找出重复的参数。你能帮我么。
#! /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.
如果使用下面的重复参数
运行./Install.sh -VO abc.txt -CON tt.txt -CON ta.txt -PASSWORD ABC -PASSWORD non
- 没有失败,这里我想在输入重复选项时抛出错误。
答案 0 :(得分:4)
只需检查是否已设置该值。
#!/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
答案 1 :(得分:2)
您可以在while循环之前使用以下代码。
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
或者你可以添加case语句来获取哪个参数是重复的。
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
让我知道它是否有效。