Bash getopts 区分“-?”来自无效选项
我希望 getopts 能够识别用户何时传递“-?
”和“-h
”并将其发送到我的帮助函数。 如果提供了无效选项,我也不希望 getopts 将用户发送到帮助功能。我想要显示一条不同的消息,告诉他们这是一个无效选项并发送到 stderr。
这是我的选项部分:
options(){
# grab options flags before entering application:
while getopts ":h?vu:d" opts; do
case "${opts}"
in
h\?) # Help
help_section
exit 0
;;
v) # Version
version
exit 0
;;
u) # units
other_units="$OPTARG"
;;
d) # Debug
debug=1
;;
\?) # Invalid options
echo "no here"
>&2 echo "[!] ERROR: Invalid Option: -$OPTARG"
exit 1
;;
esac
done
shift $((OPTIND -1))
# Run main function
main_run "$@"
}
问题:当用户输入无效选项时,getopts
不断向用户发送帮助信息。我需要确保用户认识到他们提供了无效参数;我不想派他们去帮忙。
有没有办法用getopts
来实现这个?或者在 getopts
之外构建逻辑来捕获并执行我需要的内容?
I want getopts
to recognize when a user passes "-?
" and "-h
" and send to my help function.
I also don't want getopts
to send the user to the help function if an invalid option is presented. I want a different message to display telling them it was an invalid option and send to stderr.
Here is my options section:
options(){
# grab options flags before entering application:
while getopts ":h?vu:d" opts; do
case "${opts}"
in
h\?) # Help
help_section
exit 0
;;
v) # Version
version
exit 0
;;
u) # units
other_units="$OPTARG"
;;
d) # Debug
debug=1
;;
\?) # Invalid options
echo "no here"
>&2 echo "[!] ERROR: Invalid Option: -$OPTARG"
exit 1
;;
esac
done
shift $((OPTIND -1))
# Run main function
main_run "$@"
}
Problem: getopts
keeps sending the user to help when they put an invalid option in. I need to make sure the user recognizes they provided an invalid parameter; I do not want to send them to help.
Is there a way to implement this with getopts
? Or build logic outside of getopts
to capture and perform what I need?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Bash 命令行输入示例
以下示例展示了如何采用各种类型的输入并默认为无效的输入选项。
这里发生了什么?
我们读入所有输入,并根据类型我们可以转移到下一个或转移两次。如果您看到使用了 --opt ,则它期望在之后将其设置为变量。关于您的问题的更多信息,我们接受 -?或者 - ?如果发生这种情况,它将采取帮助部分内的措施;如果这些输入都没有被处理,它将执行“*”部分中的默认值,这意味着任何输入。注意:这只是一个示例,在这种情况下,即使提供了其他输入,帮助部分也会导致脚本停止,这可能是也可能不是您个人想要做的事情。
输出示例
Bash Command Line Input Example
The following example shows how to take various types of inputs and default to an invalid input option.
What is going on here?
We read in all of the inputs and based on the type we can shift to the next or shift twice. If you see --opt is used, it is expecting something after which would be set to a variable. More on point of your issue, we accept -? or --? and if that happens it will do what is within the section of help; if none of these inputs is processed, it will do whatever the default is in the section '*' which means any input. Note: this is just an example and in this case the help section causes the script to stop even if other inputs were provided, this may or may not be what you personally are looking to do.
Example output