解析getopt参数时出错

时间:2018-02-15 20:01:33

标签: bash getopt getopts

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

./ 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 "$@"

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

谢谢, Firas

1 个答案:

答案 0 :(得分:0)

这将完成这项工作:

#!/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 "$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"
   # correct the two variable names below
   echo "Password is: $Password"        # was $KeystorePassword
   echo "common name is: $Commonname"   # was $CommonName
}
main "$@"