我通过应用一些额外的验证来解决我的问题..
#!/bin/bash
USAGE() {
echo "Invalid Option"
exit 1
}
if [ $# -eq 2 ]; then
case $1 in
-c) FLAG=1; host=$2 ;;
-h) host=$2 ;;
esac
if [ -z "$host" ]; then
case $2 in
-c) FLAG=1; host=$1;;
-h) host=$1;;
*) USAGE;;
esac
fi
else
while getopts q:c:h: OPTION
do
case ${OPTION} in
q) USAGE;;
h) host=$OPTARG;;
c) FLAG=1 ;;
*)USAGE;;
esac
done
fi
if [ $# -eq 1 ]; then host=$1 ;fi
echo Host = $host FLag = $FLAG
在所有情况下,我都在我的脚本中获取我的主机,如此输出所示。
$ ./myscript.sh server1
Host = server1 FLag =
$ ./myscript.sh -c server1
Host = server1 FLag = 1
$ ./myscript.sh server1 -c
Host = server1 FLag = 1
$ ./myscript.sh server1 -h
Host = server1 FLag =
$ ./myscript.sh -h server1
Host = server1 FLag =