【问题标题】:about getopt syntax error关于getopt语法错误
【发布时间】:2018-10-20 01:57:44
【问题描述】:

好吧,我是一个 linux bash 业余爱好者,正在玩 getopsgetop;我已经阅读了几个论坛中关于该主题的几个对话,但我似乎无法让我的代码工作。

这是一个使用getopts的小脚本,从这个论坛回收:

#!bin/bash

while getopts ":a:p:" opt; do
  case $opt in
    a) arg_1="$OPTARG"
    ;;
    p) arg_2="$OPTARG"
    ;;
    \?)
    ;;
  esac
done

printf "Argument firstArg is %s\n" "$arg_1"
printf "Argument secondArg is %s\n" "$arg_2"

它完成了它的工作:

bash test02.sh -asomestring -bsomestring2 #either with or without quotes
#Argument firstArg is somestring
#Argument secondArg is somestring2

现在,由于我想尝试长选项名称,我正在尝试getopt,试图从我在网上找到的示例中理解语法:

#!/bin/bash

temp=`getopt -o a:b: -l arga:,argb:--"$@"`
eval set --"$temp"

while true ; do
  case "$1" in
    a|arga) firstArg="$OPTARG"
    ;;
    b|argb) secondArg="$OPTARG"
    ;;
    \?)
    ;;
  esac
done

printf "Argument firstArg is %s\n" "$firstArg"
printf "Argument secondArg is %s\n" "$secondArg"

上面的代码不起作用:

bash test04.sh -a'somestring' -b'somestring2' #either with or without quotes
#getopt: invalid option -- 'b'
#Try `getopt --help' for more information.
#
bash test04.sh --arga=somestring --argb=somestring2
#getopt: unrecognized option '--argb=somestring2'
#Try `getopt --help' for more information.

你能帮我理解我的错误吗?

【问题讨论】:

  • eval set -- "$temp"中的--后面加一个空格
  • 同样在"$@"之前
  • 感谢您的帮助。我试过了,还是不行;我得到:“getopt:-s 或 --shell 参数之后的未知 shell”。我猜如果我在 argb 之后也放了一个空格,它就是从“某物”中读取“s”,即: arga:,argb:--"$@" ,结果是终端就挂在那里。

标签: linux bash getopt getopts


【解决方案1】:

-- 前后需要适当的空格。

temp=`getopt -o a:b: -l arga:,argb: -- "$@"`
eval set -- "$temp" 

在处理结果的while 循环中,您需要使用shift 命令转到下一个选项,否则您将永远继续处理相同的选项。

getopt 没有设置像$OPTARG 这样的变量,你只是使用位置参数。

while true ; do
  case "$1" in
    -a|--arga) firstArg="$2"; shift 2
    ;;
    -b|--argb) secondArg="$2"; shift 2
    ;;
    --) shift; break
    ;;
    *) echo "Bad option: $1"; shift
    ;;
  esac
done

https://www.tutorialspoint.com/unix_commands/getopt.htm查看示例

【讨论】:

  • 再次感谢您抽出宝贵时间帮助我。我进行了更改,但现在我得到了“错误选项:”的无休止打印,“选项:”之后没有打印任何内容
  • 您需要使用-- 大小写来检测选项的结尾。
  • 好的,现在循环不是无限的。剩下的问题是它给了我两个选项的“坏选项”
  • 案例需要---前缀。
  • 您知道eval set -- "$temp"$temp 复制到位置参数中,对吗?所以$1 是第一个参数,$2 是第二个参数,依此类推。每次使用shift 2,它都会删除前2个参数,因此下一个选项变为$1,其参数变为$2
猜你喜欢
  • 2022-06-19
  • 1970-01-01
  • 1970-01-01
  • 2012-11-07
  • 1970-01-01
  • 1970-01-01
  • 2019-06-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多