【发布时间】:2011-05-10 00:21:36
【问题描述】:
我想在bash 脚本中同时支持短选项和长选项,因此可以:
$ foo -ax --long-key val -b -y SOME FILE NAMES
有可能吗?
【问题讨论】:
-
虽然指定的副本专门询问
getopts,但有几个答案建议不同的方法。我同意关闭。
标签: bash getopt getopt-long
我想在bash 脚本中同时支持短选项和长选项,因此可以:
$ foo -ax --long-key val -b -y SOME FILE NAMES
有可能吗?
【问题讨论】:
getopts,但有几个答案建议不同的方法。我同意关闭。
标签: bash getopt getopt-long
getopt 支持长选项。
http://man7.org/linux/man-pages/man1/getopt.1.html
这是一个使用你的论点的例子:
#!/bin/bash
OPTS=`getopt -o axby -l long-key: -- "$@"`
if [ $? != 0 ]
then
exit 1
fi
eval set -- "$OPTS"
while true ; do
case "$1" in
-a) echo "Got a"; shift;;
-b) echo "Got b"; shift;;
-x) echo "Got x"; shift;;
-y) echo "Got y"; shift;;
--long-key) echo "Got long-key, arg: $2"; shift 2;;
--) shift; break;;
esac
done
echo "Args:"
for arg
do
echo $arg
done
$ foo -ax --long-key val -b -y SOME FILE NAMES的输出:
Got a
Got x
Got long-key, arg: val
Got b
Got y
Args:
SOME
FILE
NAMES
【讨论】:
getopt 的某些版本在参数和非选项参数中的某些字符存在问题。如果getopt --test; echo $? 输出“4”,你就可以了。如果它输出“0”,则您有一个存在此问题的版本。请参阅man getopt 了解更多信息。