[英]Combining multiple options into one single option (Getopts)
Due to my lack of thorough understanding using getopts, the title is definitely vague :0. 由于我缺乏对使用getopts的透彻了解,因此标题的名称肯定是模糊的:0。 I am currently writing a bash script and I would like to add an option that outputs the other options within the case statement in getopts.
我目前正在编写bash脚本,我想添加一个选项,该选项在getopts的case语句中输出其他选项。 For the sake of scaling, I have shortened the program.
为了扩展,我缩短了程序。
#!/bin/bash
while getopts :abc opt
do
case $opt in
a)
echo "Hello"
;;
b)
echo "Goodbye"
c)
:ab #****I WANT -c TO OUTPUT THE RESULTS OF a and b************
;;
esac
done
As you can see in option c, I would like this particular option (-c) to put out both the results of -a and -b. 正如您在选项c中看到的那样,我希望这个特定的选项(-c)可以同时显示-a和-b的结果。 Is there a way to go about this by simply making c call on option a and b?
是否可以通过简单地使c调用选项a和b来解决此问题?
you can introduce functions to reduce duplications, something like this: 您可以引入减少重复的功能,如下所示:
#!/bin/bash
do_a() {
echo "Hello"
}
do_b() {
echo "Goodbye"
}
while getopts :abc opt
do
case $opt in
a)
do_a
;;
b)
do_b
;;
c)
do_a
do_b
;;
esac
done
If you are using a recent version of Bash, instead of terminating case
clauses with ;;
如果您使用的是Bash的最新版本,请使用
;;
代替case
子句。 you could use bash specific ;;&
with multiple patterns: 您可以使用特定于bash的
;;&
多种模式:
#!/bin/bash
while getopts :abc opt
do
case $opt in
a|c)
echo "Hello"
;;&
b|c)
echo "Goodbye"
;;&
esac
done
And: 和:
$ bash script.bash -a
Hello
$ bash script.bash -c
Hello
Goodbye
Using ';;&' in place of ';;' 使用';;&'代替';;' causes the shell to test the patterns in the next clause, if any, and execute any associated command-list on a successful match.
使外壳测试下一个子句中的模式(如果有),并在成功匹配后执行任何关联的命令列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.