在 bash 中检查 getopts 状态的最佳方法是什么?
我正在使用以下脚本:
#!/bin/bash
#script to print quality of man
#unnikrishnan 24/Nov/2010
shopt -s -o nounset
declare -rx SCRIPT=${0##*/}
declare -r OPTSTRING="hm:q:"
declare SWITCH
declare MAN
declare QUALITY
if [ $# -eq 0 ];then
printf "%s -h for more information\n" "$SCRIPT"
exit 192
fi
while getopts "$OPTSTRING" SWITCH;do
case "$SWITCH" in
h) printf "%s\n" "Usage $SCRIPT -h -m MAN-NAME -q MAN-QUALITY"
exit 0
;;
m) MAN="$OPTARG"
;;
q) QUALITY="$OPTARG"
;;
\?) printf "%s\n" "Invalid option"
printf "%s\n" "$SWITCH"
exit 192
;;
*) printf "%s\n" "Invalid argument"
exit 192
;;
esac
done
printf "%s is a %s boy\n" "$MAN" "$QUALITY"
exit 0
在这个脚本中,如果我给出垃圾选项:
./getopts.sh adsas
./getopts.sh: line 32: MAN: unbound variable
您可以看到它失败。看来虽然不工作。解决它的最好方法是什么。
I am using following script :
#!/bin/bash
#script to print quality of man
#unnikrishnan 24/Nov/2010
shopt -s -o nounset
declare -rx SCRIPT=${0##*/}
declare -r OPTSTRING="hm:q:"
declare SWITCH
declare MAN
declare QUALITY
if [ $# -eq 0 ];then
printf "%s -h for more information\n" "$SCRIPT"
exit 192
fi
while getopts "$OPTSTRING" SWITCH;do
case "$SWITCH" in
h) printf "%s\n" "Usage $SCRIPT -h -m MAN-NAME -q MAN-QUALITY"
exit 0
;;
m) MAN="$OPTARG"
;;
q) QUALITY="$OPTARG"
;;
\?) printf "%s\n" "Invalid option"
printf "%s\n" "$SWITCH"
exit 192
;;
*) printf "%s\n" "Invalid argument"
exit 192
;;
esac
done
printf "%s is a %s boy\n" "$MAN" "$QUALITY"
exit 0
In this if I am giving the junk option :
./getopts.sh adsas
./getopts.sh: line 32: MAN: unbound variable
you can see it fails. it seems while is not working. What is the best way to solve it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当没有选项参数时,
getopts
内置函数返回 1(“false”)。因此,除非您有以
-
开头的选项参数,否则您的while
永远不会执行。请注意 bash(1) 的 getopts 部分的最后一段:
The
getopts
builtin returns 1 ("false") when there are no option arguments.So, your
while
never executes unless you have option arguments beginning with a-
.Note the last paragraph in the getopts section of bash(1):
如果您绝对需要 MAN,那么我建议您不要将其设为选项参数,而是将其设为位置参数。选项应该是可选的。
但是,如果您想将其作为一个选项来执行,那么请执行以下操作:
更好的是,在退出之前打印使用消息 - 将其拉出到函数中,以便您可以与 -h 选项的情况共享它。
If you absolutely require MAN, then i suggest you don't make it an option parameter, but a positional parameter. Options are supposed to be optional.
However, if you want to do it as an option, then do:
Even better, print the usage message before exiting - pull it out into a function so you can share it with the -h option's case.
“最佳”解决方案是主观的。一种解决方案是为那些可以通过选项设置的变量提供默认值。
The "best" solution is subjective. One solution would be to give default values to those variables that can be set by options.