bash 重新读取 $OPTARG 以获取可选标志?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18414054/
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
Rreading $OPTARG for optional flags?
提问by earth
I'd like to be able to accept both mandatory and optional flags in my script. Here's what I have so far.
我希望能够在我的脚本中接受强制性和可选标志。这是我到目前为止所拥有的。
#!bin/bash
while getopts ":a:b:cdef" opt; do
case $opt in
a ) APPLE="$OPTARG";;
b ) BANANA="$OPTARG";;
c ) CHERRY="$OPTARG";;
d ) DFRUIT="$OPTARG";;
e ) EGGPLANT="$OPTARG";;
f ) FIG="$OPTARG";;
\?) echo "Invalid option: -"$OPTARG"" >&2
exit 1;;
: ) echo "Option -"$OPTARG" requires an argument." >&2
exit 1;;
esac
done
echo "Apple is "$APPLE""
echo "Banana is "$BANANA""
echo "Cherry is "$CHERRY""
echo "Dfruit is "$DFRUIT""
echo "Eggplant is "$EGGPLANT""
echo "Fig is "$FIG""
However, the output for the following:
但是,以下输出:
bash script.sh -a apple -b banana -c cherry -d dfruit -e eggplant -f fig
...outputs this:
...输出这个:
Apple is apple
Banana is banana
Cherry is
Dfruit is
Eggplant is
Fig is
As you can see, the optional flags are not pulling the arguments with $OPTARG as it does with the required flags. Is there a way to read $OPTARG on optional flags without getting rid of the neat ":)" error handling?
如您所见,可选标志不会像使用必需标志那样使用 $OPTARG 提取参数。有没有办法在不摆脱整洁的“:)”错误处理的情况下读取可选标志上的 $OPTARG ?
=======================================
========================================
EDIT:I wound up following the advice of Gilbert below. Here's what I did:
编辑:我听从了下面吉尔伯特的建议。这是我所做的:
#!/bin/bash
if [[ "" =~ ^((-{1,2})([Hh]$|[Hh][Ee][Ll][Pp])|)$ ]]; then
print_usage; exit 1
else
while [[ $# -gt 0 ]]; do
opt=""
shift;
current_arg=""
if [[ "$current_arg" =~ ^-{1,2}.* ]]; then
echo "WARNING: You may have left an argument blank. Double check your command."
fi
case "$opt" in
"-a"|"--apple" ) APPLE=""; shift;;
"-b"|"--banana" ) BANANA=""; shift;;
"-c"|"--cherry" ) CHERRY=""; shift;;
"-d"|"--dfruit" ) DFRUIT=""; shift;;
"-e"|"--eggplant" ) EGGPLANT=""; shift;;
"-f"|"--fig" ) FIG=""; shift;;
* ) echo "ERROR: Invalid option: \""$opt"\"" >&2
exit 1;;
esac
done
fi
if [[ "$APPLE" == "" || "$BANANA" == "" ]]; then
echo "ERROR: Options -a and -b require arguments." >&2
exit 1
fi
Thanks so much, everyone. This works perfectly so far.
非常感谢大家。到目前为止,这非常有效。
采纳答案by Gilbert
Most shell getopts have been annoying me for a long time, including lack of support of optional arguments.
大多数 shell getopts 一直困扰着我很长时间,包括缺乏对可选参数的支持。
But if you are willing to use "--posix" style arguments, visit bash argument case for args in $@
但是,如果您愿意使用“--posix”样式参数,请访问$@ 中 args 的 bash 参数案例
回答by nneonneo
:
means "takes an argument", not "mandatory argument". That is, an option character not followed by :
means a flag-style option (no argument), whereas an option character followed by :
means an option with an argument.
:
意思是“需要一个论点”,而不是“强制性论点”。也就是说,后面没有跟随的选项字符:
表示标志样式选项(无参数),而后面跟随的选项字符:
表示带有参数的选项。
Thus, you probably want
因此,你可能想要
getopts "a:b:c:d:e:f:" opt
If you want "mandatory" options (a bit of an oxymoron), you can check after argument parsing that your mandatory option values were all set.
如果您想要“强制”选项(有点矛盾),您可以在参数解析后检查您的强制选项值是否已全部设置。
回答by earth
It isn't easy... Any "optional" option arguments must actually be required as far as getopts
will know. Of course, an optional argument must be a part of the same argument to the script as the option it goes with. Otherwise an option -f
with an optional argument and an option -a
with a required argument can get confused:
这并不容易......据getopts
所知,实际上必须需要任何“可选”选项参数。当然,可选参数必须是脚本的同一个参数的一部分,作为它所使用的选项。否则,-f
带有可选参数的选项-a
和带有必需参数的选项可能会混淆:
# Is -a an option or an argument?
./script.sh -f -a foo
# -a is definitely an argument
./script.sh -f-a foo
The only way to do this is to test whether the option and its argument are in the same argument to the script. If so, OPTARG is the argument to the option. Otherwise, OPTIND must be decremented by one. Of course, the option is now required to have an argument, meaning a character will be found when an option is missing an argument. Just use another case
to determine if any options are required:
执行此操作的唯一方法是测试选项及其参数是否在脚本的同一参数中。如果是,则 OPTARG 是选项的参数。否则,OPTIND 必须减一。Of course, the option is now required to have an argument, meaning a character will be found when an option is missing an argument. 只需使用另一个case
来确定是否需要任何选项:
while getopts ":a:b:c:d:e:f:" opt; do
case $opt in
a) APPLE="$OPTARG";;
b) BANANA="$OPTARG";;
c|d|e|f)
if test "$OPTARG" = "$(eval echo '$'$((OPTIND - 1)))"; then
OPTIND=$((OPTIND - 1))
else
case $opt in
c) CHERRY="$OPTARG";;
d) DFRUIT="$OPTARG";;
...
esac
fi ;;
\?) ... ;;
:)
case "$OPTARG" in
c|d|e|f) ;; # Ignore missing arguments
*) echo "option requires an argument -- $OPTARG" >&2 ;;
esac ;;
esac
done
This has worked for me so far.
到目前为止,这对我有用。
回答by Will Charlton
For bash, this is my favorite way to parse/support cli args. I used getopts and it was too frustrating that it wouldn't support long options. I do like how it works otherwise - especially for built-in functionality.
对于 bash,这是我最喜欢的解析/支持 cli 参数的方式。我使用了 getopts,它不支持长选项太令人沮丧了。我确实喜欢它的其他工作方式 - 特别是对于内置功能。
usage()
{
echo "usage: script -ffilename
script -f
-OPT1 <opt1_arg> -OPT2"
}
while [ "`echo | cut -c1`" = "-" ]
do
case "" in
-OPT1)
OPT1_ARGV=
OPT1_BOOL=1
shift 2
;;
-OPT2)
OPT2_BOOL=1
shift 1
;;
*)
usage
exit 1
;;
esac
done
Short, simple. An engineer's best friend!
简短,简单。工程师最好的朋友!
I think this can be modified to support "--" options as well...
我认为这也可以修改以支持“--”选项......
Cheers =)
干杯 =)
回答by Jonathan Leffler
Understanding bash
's getopts
理解bash
的getopts
The bash
manual page (quoting the version 4.1 manual) for getopts
says:
该bash
手册页(报价4.1版手册)的getopts
说:
getopts optstring name
[args]
getopts
is used by shell scripts to parse positional parameters. optstringcontains the option characters to be recognized; if a character is followed by a colon, the option is expected to have an argument, which should be separated from it by white space. The colon (‘:') and question mark (‘?') may not be used as option characters. Each time it is invoked,getopts
places the next option in the shell variable name, initializing nameif it does not exist, and the index of the next argument to be processed into the variableOPTIND
.OPTIND
is initialized to 1 each time the shell or a shell script is invoked. When an option requires an argument,getopts
places that argument into the variableOPTARG
. The shell does not resetOPTIND
automatically; it must be manually reset between multiple calls togetopts
within the same shell invocation if a new set of parameters is to be used.When the end of options is encountered,
getopts
exits with a return value greater than zero.OPTIND
is set to the index of the first non-option argument, and nameis set to ‘?'.
getopts
normally parses the positional parameters, but if more arguments are given in args,getopts
parses those instead.
getopts
can report errors in two ways. If the first character of optstringis a colon, silent error reporting is used. In normal operation diagnostic messages are printed when invalid options or missing option arguments are encountered. If the variableOPTERR
is set to 0, no error messages will be displayed, even if the first character of optstringis not a colon.If an invalid option is seen,
getopts
places ‘?' into nameand, if not silent, prints an error message and unsetsOPTARG
. Ifgetopts
is silent, the option character found is placed inOPTARG
and no diagnostic message is printed. If a required argument is not found, andgetopts
is not silent, a question mark (‘?') is placed in name,OPTARG
is unset, and a diagnostic message is printed. Ifgetopts
is silent, then a colon (‘:') is placed in nameandOPTARG
is set to the option character found.
getopts optstring name
[args]
getopts
shell 脚本使用它来解析位置参数。optstring包含要识别的选项字符;如果一个字符后跟一个冒号,则该选项应该有一个参数,应该用空格将它与它分开。冒号 (':') 和问号 ('?') 不能用作选项字符。每次调用时,getopts
将下一个选项放在 shell 变量name 中,如果name不存在则初始化name,并将下一个要处理的参数的索引放入变量中OPTIND
。OPTIND
每次调用 shell 或 shell 脚本时都会初始化为 1。当一个选项需要一个参数时,getopts
将该参数放入变量中OPTARG
. 外壳不会OPTIND
自动重置;如果要使用getopts
一组新参数,则必须在同一个 shell 调用内的多次调用之间手动重置它。当遇到选项结束时,
getopts
以大于零的返回值退出。OPTIND
设置为第一个非选项参数的索引,名称设置为“?”。
getopts
通常分析位置参数,但是如果有更多的参数在给定的ARGS,getopts
解析那些代替。
getopts
可以通过两种方式报告错误。如果optstring的第一个字符是冒号,则使用静默错误报告。在正常操作中,当遇到无效选项或缺少选项参数时会打印诊断消息。如果变量OPTERR
设置为 0,即使optstring的第一个字符不是冒号,也不会显示错误消息。如果看到无效选项,则
getopts
放置 '?' 进入name,如果不是静默,则打印错误消息并取消设置OPTARG
。如果getopts
是静默,则将找到的选项字符放入,OPTARG
并且不打印诊断消息。如果未找到必需的参数,并且getopts
不是无声的,则在name 中放置一个问号 ('?') ,OPTARG
未设置,并打印诊断消息。如果getopts
是无声的,则冒号 (':') 放在name 中并OPTARG
设置为找到的选项字符。
Note that:
注意:
The leading colon in the option string puts
getopts
into silent mode; it does not generate any error messages.The description doesn't mention anything about optional option arguments.
选项字符串中的前导冒号
getopts
进入静默模式;它不会生成任何错误消息。描述没有提到任何关于可选选项参数的内容。
I'm assuming that you are after functionality akin to:
我假设您追求的功能类似于:
#!/bin/bash
while getopts ":a:b:c:d:e:f:" opt; do
case $opt in
a ) APPLE="$OPTARG";;
b ) BANANA="$OPTARG";;
c ) CHERRY="$OPTARG";;
d ) DFRUIT="$OPTARG";;
e ) EGGPLANT="$OPTARG";;
f ) FIG="$OPTARG";;
\?) echo "Invalid option: -"$OPTARG"" >&2
exit 1;;
: ) echo "Option -"$OPTARG" requires an argument." >&2
exit 1;;
esac
done
echo "Apple is "$APPLE""
echo "Banana is "$BANANA""
echo "Cherry is "$CHERRY""
echo "Dfruit is "$DFRUIT""
echo "Eggplant is "$EGGPLANT""
echo "Fig is "$FIG""
where the flag f
(-f
) optionally accepts an argument. This is not supported by bash
's getopts
command. The POSIX function getopt()
barely supports that notation. In effect, only the last option on a command line can have an optional argument under POSIX.
其中标志f
( -f
) 可选择接受一个参数。bash
的getopts
命令不支持此操作。POSIX 函数getopt()
几乎不支持这种表示法。实际上,在 POSIX 下,只有命令行上的最后一个选项可以有一个可选参数。
What are the alternatives?
有哪些替代方案?
In part, consult Using getopts
in bash
shell script to get long and short command-line options.
部分地,请参阅在shell 脚本中使用以获取长短命令行选项getopts
bash
。
The GNU getopt
(singular!) program is a complex beastie that supports long and short options and supports optional arguments for long options (and uses GNU getopt(3)
. Tracking its source is entertaining; the link on the page at die.net is wrong; you'll find it in a sub-directory under ftp://ftp.kernel.org/pub/linux/utils/util-linux(without the -ng
). I've not tracked down a location at http://www.gnu.org/or http://www.fsf.org/that contains it.
GNU getopt
(单数!)程序是一个复杂的野兽,它支持长选项和短选项并支持长选项的可选参数(并使用 GNU getopt(3)
。跟踪它的来源很有趣;die.net 页面上的链接是错误的;你会在ftp://ftp.kernel.org/pub/linux/utils/util-linux下的子目录中找到它(没有-ng
)。我没有在http://www.gnu.org 找到一个位置/或包含它的http://www.fsf.org/。