简体   繁体   English

Getopts默认大小写bash脚本

[英]Getopts default case bash script

I want to use getopts but the default case doesn't work. 我想使用getopts,但是默认情况下不起作用。

The code that I tried is: 我尝试的代码是:

while getopts "sdp" arg; do
case "$arg" in
s) 
    echo "1" 
;;
p)
    echo "2" 
;;
d) 
   echo "3" 
;;
*) 
   echo "default"
;;
esac

when I run the process: ./myTask 当我运行该过程时:./myTask

I didn't receive any output 我没有收到任何输出

It's working as intended. 它按预期工作。

The default case is not to handle the case where you don't have arguments, but the case where you supply invalid arguments: 默认情况不是处理没有参数的情况,而是提供无效参数的情况:

$ ./myTest -X
./myTest: illegal option -- X
default

Normally you would write a usage message in this case. 通常,在这种情况下,您将编写使用情况消息。

That's the default of the case statement, but it means something specific in the context of getopts : That you have an option defined but no clause to handle it. 这是case语句的默认值,但这意味着在getopts上下文中特定的东西:您定义了一个选项,但没有子句可以处理它。

If you run ./myTask -z , for example, you will see the output of "default" as @that_other_guy states in another answer here. 例如,如果运行./myTask -z ,您将在此处的另一个答案中看到@that_other_guy声明的“默认”输出。

If you want to output something that indicates that no option was supplied: 如果要输出指示未提供任何选项的内容:

Then after the while getopts block but before the shift $(($OPTIND - 1)) line, do this (with whatever processing you want inside the if block: 然后在while getopts块之后但在shift $(($OPTIND - 1))行之前,执行此操作(对if块进行所需的任何处理:

if ((OPTIND == 1))
then
    echo "No options specified"
fi

Note that this does not indicate that no arguments were specified (eg ./myTask as in your question). 请注意,这并不表示未指定任何参数 (例如,如您问题中的./myTask )。 To do something with that, add this after the shift line: 要执行此操作,请shift之后添加以下内容:

if (($# == 0))
then
    echo "No positional arguments specified"
fi

Please see a reference implementation of a getopts function in my answer here . 请在我的答案中查看 getopts函数的参考实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM