解析 getopt 参数时出错

error parsing getopt parameters

当我尝试 运行 如下脚本时:

./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 "" in
       -t | --certtype) CertType="" ; shift;;
       -p | --password) Password="" ; shift;;
       -c | --commonname) Commonname="" ;shift;;
       -- ) shift; break;;
       -* ) echo "[=11=]: error - unrecognized option " 1>&2; exit 1;; 
       *  ) break;;
      esac
      shift
   done

   echo "Cert type is: $CertType"
   echo "Password is: $KeystorePassword"
   echo "common name is: $CommonName"
}
main "$@"

我在上面的代码中遗漏了什么吗?

谢谢, 菲拉斯

这将完成工作:

#!/bin/bash

main()
{
   set -x
   local BIN_PATH CertType Password Commonname 
   BIN_PATH="keytool"
   # add commas between the long options
   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 "" in
       -t | --certtype) CertType="" ; shift;;
       -p | --password) Password="" ; shift;;
       -c | --commonname) Commonname="" ;shift;;
       -- ) shift; break;;
       -* ) echo "[=10=]: error - unrecognized option " 1>&2; exit 1;; 
       *  ) break;;
      esac
      shift
   done

   echo "Cert type is: $CertType"
   # correct the two variable names below
   echo "Password is: $Password"        # was $KeystorePassword
   echo "common name is: $Commonname"   # was $CommonName
}
main "$@"