【发布时间】: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. 我删除了可选参数(我不想这样做),但仍然收到错误消息。
【问题讨论】: