【发布时间】:2018-07-26 16:30:21
【问题描述】:
当我尝试如下运行脚本时:
./myscript.sh --certtype ca --password xyz --commonname xyz
我收到以下错误:
+ local BIN_PATH CertType Password Commonname
+ BIN_PATH=keytool
++ getopt -u -o t:p:c -l certtype:password:commonname -- --certtype ca --password xyz --commonname xyz
getopt: unrecognized option '--password'
getopt: unrecognized option '--commonname'
+ options=' --certtype:password:commonname -- ca xyz xyz'
+ echo 'Error on parsing parameters'
Error on parsing parameters
+ exit 1
下面是我要执行的脚本:
#!/bin/bash
main()
{
set -x
local BIN_PATH CertType Password Commonname
BIN_PATH="keytool"
if ! options=$(getopt -u -o t:p:c:: -l certtype:password:commonname:: -- "$@")
then
# something went wrong, getopt will put out an error message for us
echo "Error on parsing parameters"
exit 1
fi
set -- $options
while [ $# -gt 0 ]
do
case "$1" in
-t | --certtype) CertType="$2" ; shift;;
-p | --password) Password="$2" ; shift;;
-c | --commonname) Commonname="$2" ;shift;;
-- ) shift; break;;
-* ) echo "$0: error - unrecognized option $1" 1>&2; exit 1;;
* ) break;;
esac
shift
done
echo "Cert type is: $CertType"
echo "Password is: $KeystorePassword"
echo "common name is: $CommonName"
}
main "$@"
我在上面的代码中遗漏了什么吗?
谢谢, 费拉斯
【问题讨论】:
-
顺便说一句:shellcheck.net
-
感谢 Pierre,但我认为每个选项后都需要一个冒号,因为每个选项标志都会读取一个值。
-
@F.K.:对不起:我刚刚看到我的错误,但没有时间纠正它。
-
@F.K.:在这种情况下,您还需要在最后一个 c:
t:p:c: -
使用 eval 和引号正确处理带空格的参数至关重要:
eval set -- "$options"