使用 getopt 解析长参数会跳到第一个值
Using getopt to parse long arguments skips to the first value
我正在尝试使用 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: ";
echo "And value seen: ";
case "" in
--firstName ) echo "First name: "; shift 2;
;;
--lastName )
echo "Last Name: ";
shift 2;
;;
--age ) if [ -z "" ];
then
echo "Age is not specified.";
else
echo "Age specifed: "; 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. 我已经删除了可选参数(我不想这样做),但仍然出现错误。
上面的代码有两个问题:
- 脚本只解析长参数。如果仅使用长参数,
getopt
的正确调用如下:
OPTS=$(getopt -o '' -l "firstName:,lastName:,age::" -- "$@");
注意 -o
标志旁边的 ''
。 Getopt 要求 -o
标志留空以防没有短格式参数。
- 此脚本的参数需要用
=
符号指定。
脚本的示例调用是:
./longArgumentsParsing.bash --firstName=sriram --lastName=shankar --age=30
.
我正在尝试使用 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: ";
echo "And value seen: ";
case "" in
--firstName ) echo "First name: "; shift 2;
;;
--lastName )
echo "Last Name: ";
shift 2;
;;
--age ) if [ -z "" ];
then
echo "Age is not specified.";
else
echo "Age specifed: "; 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. 我已经删除了可选参数(我不想这样做),但仍然出现错误。
上面的代码有两个问题:
- 脚本只解析长参数。如果仅使用长参数,
getopt
的正确调用如下:
OPTS=$(getopt -o '' -l "firstName:,lastName:,age::" -- "$@");
注意 -o
标志旁边的 ''
。 Getopt 要求 -o
标志留空以防没有短格式参数。
- 此脚本的参数需要用
=
符号指定。
脚本的示例调用是:
./longArgumentsParsing.bash --firstName=sriram --lastName=shankar --age=30
.