【问题标题】:Bash: getopts - ignoring option?Bash:getopts - 忽略选项?
【发布时间】:2013-11-26 08:31:31
【问题描述】:

有一些带有getopts 的脚本。它包括下一个:

while getopts "hlcpx:" opt; do
  case $opt in
    h)
      usage && exit 1
      ;;
    l)
      last=1
      current=""
      ;;
    c)
      current=1
      last=""
      ;;
    p)
      prints=1
      exports=""
      ;;
    x)
      exports=1
      prints=""
      ;;
    \?)
      usage && exit 1
      ;;
  esac
done

echo "Using: current=$current last=$last prints=$prints exports=$exports"

但是 - 当我使用选项 -x-c 运行它时,我得到了:

$ ./version.sh -x -l
Using: current= last= prints= exports=1

$ ./version.sh -x -c
Using: current= last= prints= exports=1

如果我删除 : - 它可以正常工作:

$ cat version.sh | grep whil
while getopts "hlcpx" opt; do

$ ./version.sh -x -c
Using: current=1 last= prints= exports=1

$ ./version.sh -x -l
Using: current= last=1 prints= exports=1

我做错了什么?谢谢。

【问题讨论】:

    标签: bash getopts


    【解决方案1】:

    getopts 按设计工作。如果您不需要将参数传递给-x 选项,请不要在getopts 选项字符串中将: 附加到x

    或者,使用具有预期语法的脚本,例如:

    ./version.sh -x foo -c
    

    【讨论】:

    • 对不起,我是白痴:D 我真的不需要 $OPTARG 。
    猜你喜欢
    • 2021-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-05
    • 2016-03-10
    • 2010-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多