【问题标题】:error parsing getopt parameters解析 getopt 参数时出错
【发布时间】: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"

标签: bash getopt getopts


【解决方案1】:

这样就可以了:

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

【讨论】:

  • 皮埃尔和格伦,非常感谢!正如你们都指出的那样,这是长名称中缺少的逗号。
  • 皮埃尔,我接受了你的解决方案。感谢您的帮助。
猜你喜欢
  • 2010-11-06
  • 1970-01-01
  • 2023-03-07
  • 1970-01-01
  • 1970-01-01
  • 2021-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多