1

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

这是一个使用 的小脚本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.

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

4

1 回答 1

2

前后需要适当的空格--

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上的示例

于 2018-05-09T22:21:01.710 回答