如何在 bash 中同时支持短选项和长选项?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4180880/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to support both short and long options at the same time in bash?
提问by Xiè Jìléi
I want to support both short and long options in bash
scripts, so one can:
我想在bash
脚本中同时支持短选项和长选项,因此可以:
$ foo -ax --long-key val -b -y SOME FILE NAMES
is it possible?
是否可以?
回答by Brian Clements
getopt
supports long options.
getopt
支持长选项。
http://man7.org/linux/man-pages/man1/getopt.1.html
http://man7.org/linux/man-pages/man1/getopt.1.html
Here is an example using your arguments:
这是使用您的参数的示例:
#!/bin/bash
OPTS=`getopt -o axby -l long-key: -- "$@"`
if [ $? != 0 ]
then
exit 1
fi
eval set -- "$OPTS"
while true ; do
case "" 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: "; shift 2;;
--) shift; break;;
esac
done
echo "Args:"
for arg
do
echo $arg
done
Output of $ foo -ax --long-key val -b -y SOME FILE NAMES
:
的输出$ 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