关于 getopt 语法错误

about getopt syntax error

好吧,我是一个 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 "" 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.

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

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

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

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

getopt不像$OPTARG那样设置变量,你只是使用位置参数。

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

参见 https://www.tutorialspoint.com/unix_commands/getopt.htm

中的示例