我在Bash中有以下代码:
declare {BPM_USERNAME,BPM_PASSWORD,HOST,TARGET_IP,OVERRIDE_STATUS}=''
OPTS=`getopt -a --longoptions username:,password:,csc:,ip:,override: -n "$0" -- "$@"`
eval set -- "$OPTS"
if [ $? != 0 ] ; then echo "Failed parsing options." >&2 ; exit 1 ; fi
while true; do
echo ""
echo $OPTS
echo $1
echo $2
case "$1" in
--username )
BPM_USERNAME=$2
shift 2
;;
--password )
BPM_PASSWORD=$2
shift 2
;;
--csc )
HOST=$2
shift 2
;;
--ip )
TARGET_IP=$2
shift 2
;;
--override )
OVERRIDE_STATUS=$2
shift 2
;;
--)
shift
echo "Breaking While loop"
break
;;
*)
echo ""
echo "Error in given Parameters. Undefined: "
echo $*
echo ""
echo "Usage: $0 [--username BPM_USERNAME] [--password BPM_PASSWORD] [--ip IP ADDRESS_OF_VyOS/BPM] [--csc CLIENT_SHORT_CODE] [--override TRUE/FALSE]"
exit 1
esac
done
我向Bash提供以下命令(脚本名称为UpdateSSL.sh):
./UpdateSSL.sh -username bpmadmin -password bpmadmin -ip 10.91.201.99 -csc xyz -override False
但是我没有解析选项,而是回到了以下结果(显示while循环进入*)
情况):
'bpmadmin' --password 'bpmadmin' --ip '10.91.201.99' --csc 'xyz' --override 'False' --
bpmadmin
--password
Error in given Parameters. Undefined:
bpmadmin --password bpmadmin --ip 10.91.201.99 --csc xyz --override False --
Usage: ./UpdateSSL.sh [--username BPM_USERNAME] [--password BPM_PASSWORD] [--ip IP ADDRESS_OF_VyOS/BPM] [--csc CLIENT_SHORT_CODE] [--override TRUE/FALSE]
我不知道我做错了什么。
答案 0 :(得分:1)
答案实际上在man page:
的最后如果您根本不想要任何短选项变量,则语法不是很直观(您必须将它们显式设置为空字符串)。
为了使getopt
在没有短选项的情况下运行,您必须手动指定-o ''
作为第一个参数。我做了一些其他更改,以下内容适用于我的系统(请参阅***
标记):
#!/bin/bash
# *** Make sure you have a new enough getopt to handle long options (see the man page)
getopt -T &>/dev/null
if [[ $? -ne 4 ]]; then echo "Getopt is too old!" >&2 ; exit 1 ; fi
declare {BPM_USERNAME,BPM_PASSWORD,HOST,TARGET_IP,OVERRIDE_STATUS}=''
OPTS=$(getopt -o '' -a --longoptions 'username:,password:,csc:,ip:,override:' -n "$0" -- "$@")
# *** Added -o '' ; surrounted the longoptions by ''
if [[ $? -ne 0 ]] ; then echo "Failed parsing options." >&2 ; exit 1 ; fi
# *** This has to be right after the OPTS= assignment or $? will be overwritten
set -- $OPTS
# *** As suggested by chepner
while true; do
# ... no changes in the while loop
done