【问题标题】:Using getopt to parse long arguments skips to the first value使用 getopt 解析长参数会跳到第一个值
【发布时间】:2016-04-20 11:19:12
【问题描述】:

我正在尝试使用getopt 来解析长参数(其中一些是强制性的,而另一些则不是)。代码:

#!/bin/bash

# firstName is compulsory, age is not and lastName is again compulsory.

OPTS=`getopt --long firstName:,age::,lastName: -n 'longArgumentsParsing' -- "$@"`

if [ $? != 0 ] ; then echo "Failed parsing options." >&2 ; exit 1 ; fi

#echo "$OPTS"
eval set -- "$OPTS"

while true; do
  echo "Argument seen: $1";
  echo "And value seen: $2";
  case "$1" in

    --firstName ) echo "First name: $2"; shift 2;
        ;;

    --lastName )
        echo "Last Name: $2";
        shift 2;
        ;;

    --age ) if [ -z "$2" ];
            then
              echo "Age is not specified.";
            else
              echo "Age specifed: $2"; shift 2;
            fi
            ;;

    -- ) shift; break ;;

    * ) break ;;
  esac
done

每次我使用./longArgumentsParsing --firstName sriram --age 30 运行它时,程序都会以以下输出退出:

Argument seen: sriram
And value seen: --lastName  

程序显然无法正确解析输入键和参数值对。为什么?我哪里错了?

更新:

根据this answer,我尝试自己调试: 命令行:
set -- --firstName sriram --lastName shankar 然后:
OPTS=$(getopt -l firstName:,lastName: -- "$@");
获取输出:
echo $?; echo "$OPTS"
0 'sriram' --lastName 'shankar' --

我的问题:
1. 我怎样才能使以上内容正确?
2. 我删除了可选参数(我不想这样做),但仍然收到错误消息。

【问题讨论】:

    标签: bash getopt


    【解决方案1】:

    上面的代码有两个问题:

    1. 脚本只解析长参数。 getopt 的正确调用,以防仅使用长参数:

    OPTS=$(getopt -o '' -l "firstName:,lastName:,age::" -- "$@");

    注意-o 标志旁边的''。 Getopt 要求 -o 标志留空,以防没有短格式参数。

    1. 需要使用= 符号指定此脚本的参数。
      脚本调用示例如下:
      ./longArgumentsParsing.bash --firstName=sriram --lastName=shankar --age=30

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-26
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-06
      • 2018-07-26
      • 1970-01-01
      相关资源
      最近更新 更多