[英]Override invalid option message with getopts in bash
I am using getopts
to track options that are given to my script. 我正在使用
getopts
来跟踪提供给脚本的选项。 However, I want to able to detect whether an option that was specified is invalid. 但是,我希望能够检测到指定的选项是否无效。 I can do this, but it will always echo a message that I haven't written.
我可以这样做,但是它总是会回显我未写的消息。
The result 结果
my.sh: illegal option -- x
Error: Invalid option was specified --
What I want to achieve 我想要达到的目标
Error: Invalid option was specified --
A snippet of my code 我的代码片段
while getopts g:r: option; do
case $option in
g) guesses=$OPTARG;;
r) range=$OPTARG;;
?) echo "Error: Invalid option was specified -- $OPTARG";;
esac
done
How can I achieve the desired result? 如何获得理想的结果?
Assuming you want two short options -g
and -r
, the following example will not trigger the illegal option
message on passing -x
: 假设您需要两个简短的选项
-g
和-r
,以下示例在传递-x
不会触发illegal option
消息:
while getopts ":g :r" option; do
case $option in
g) guesses=$OPTARG;;
r) range=$OPTARG;;
?) echo "Error: Invalid option was specified -$OPTARG";;
esac
done
通过在标志之前添加:
,我告诉getopts
我想控制不在我设置的列表中的标志。
In bash you can set OPTERR to 0 before commencing parsing: 在bash中,您可以在开始解析之前将OPTERR设置为0:
OPTERR=0
while getopts 'option string' opt; do
echo "opt = $opt"
echo "OPTIND = $OPTIND"
echo "OPTARG = $OPTARG"
echo "OPTERR = $OPTERR"
done
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.