使用getopt分析命令行参数时,可以在选项标记和所需参数的参数之间插入一个空格,但不能插入可选参数。可选参数只有在选项后面才会被解析。为什么不能使用getopt在选项和可选参数之间有空格?
TEMP=`getopt -o p:q:: -n 'mkqueue.sh' -- "[email protected]"`
if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi
# Note the quotes around `$TEMP': they are essential!
eval set -- "$TEMP"
# Now go through all the options
while true ; do
case "$1" in
-p) echo "Option p, argument \`$2'" ; shift 2 ;;
-q)
case "$2" in
"") echo "Option q, no argument"; shift 2 ;;
*) echo "Option q, argument \`$2'" ; shift 2 ;;
esac ;;
--) shift ; break ;;
*) echo "Internal error!" ; exit 1 ;;
esac
done
(在此基础上:http://software.frodo.looijaard.name/getopt/docs/getopt-parse.bash)
当我运行该脚本没有它的工作原理的可选参数:
./mkqueue.sh -p adfsa -q
Option p, argument `adfsa'
Option q, no argument
如果我尝试添加可选的参数与以-q它之间的空间不起作用:
./mkqueue.sh -p adfsa -q sdfasdfa
Option p, argument `adfsa'
Option q, no argument
它的作品,如果你没有作为尽管所需要的论据适用于空间:
./mkqueue.sh -p adfsa -qsdfasdfa
Option p, argument `adfsa'
Option q, argument `sdfasdfa'
是否有解决方案?
如果它被允许,你会得到另一个问题。假设你的程序也接受一个位置参数。应该将'./a.out -q foo bar'解析为'./a.out -qfoo bar'还是'./a.out -q - foo bar'? – 5gon12eder 2014-10-17 19:11:59
@ 5gon12eder,如果你有这个答案,你至少会得到我的赞赏。它解释了“为什么”,这是这个问题的标题所要求的。 :) – 2014-10-17 19:41:59