切换案例并发生故障?
我正在寻找 Bash 中带有失败案例的 switch 语句的正确语法(最好不区分大小写)。 在 PHP 中,我会这样编程:
switch($c) {
case 1:
do_this();
break;
case 2:
case 3:
do_what_you_are_supposed_to_do();
break;
default:
do_nothing();
}
我想在 Bash 中进行相同的操作:
case "$C" in
"1")
do_this()
;;
"2")
"3")
do_what_you_are_supposed_to_do()
;;
*)
do_nothing();
;;
esac
这在某种程度上不起作用:当 $C 为 2 OR 3 时,应该触发函数 do_what_you_are_supposited_to_do()
。
I am looking for the correct syntax of the switch statement with fallthrough cases in Bash (ideally case-insensitive).
In PHP I would program it like:
switch($c) {
case 1:
do_this();
break;
case 2:
case 3:
do_what_you_are_supposed_to_do();
break;
default:
do_nothing();
}
I want the same in Bash:
case "$C" in
"1")
do_this()
;;
"2")
"3")
do_what_you_are_supposed_to_do()
;;
*)
do_nothing();
;;
esac
This somehow doesn't work: function do_what_you_are_supposed_to_do()
should be fired when $C is 2 OR 3.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
最近的
bash
版本允许使用;&
代替;;
进行失败:它们还允许通过使用
;;&
恢复案例检查。样本输出
Recent
bash
versions allow fall-through by using;&
in stead of;;
:they also allow resuming the case checks by using
;;&
there.sample output
()
,除非您想定义它们。[23]
来匹配2
或3
''
括起来,而不是""
如果包含在
""
中,解释器(不必要)会在匹配之前尝试扩展值中可能的变量。对于不区分大小写的匹配,您可以使用字符类(例如
[23]
):但是
abra
没有命中,因为它将与第一个大小写匹配。如果需要,您可以在第一种情况下省略
;;
,以便在以下情况下继续测试匹配。 (;;
跳转到esac
)()
behind function names in bash unless you like to define them.[23]
in case to match2
or3
''
instead of""
If enclosed in
""
, the interpreter (needlessly) tries to expand possible variables in the value before matching.For case insensitive matching, you can use character classes (like
[23]
):But
abra
didn't hit anytime because it will be matched by the first case.If needed, you can omit
;;
in the first case to continue testing for matches in following cases too. (;;
jumps toesac
)试试这个:
Try this:
如果值是整数,则可以使用
[2-3]
,或者对于非连续值可以使用[5,7,8]
。如果值是字符串,那么您可以使用
|
。If the values are integer then you can use
[2-3]
or you can use[5,7,8]
for non continuous values.If the values are string then you can use
|
.使用竖线 (
|
) 表示“或”。Bash 参考手册:条件构造。
案例
Use a vertical bar (
|
) for "or".Bash Reference Manual: Conditional Constructs.
case