bash 如何使case语句匹配数字范围?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25481799/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make case statement match a number range?
提问by shamik
I'm running a switch case with column numbers which can be in the range 0 - 50. Now each case supports discrete column number and I observe its failure.
我正在运行一个列号可以在 0 - 50 范围内的 switch case。现在每个 case 都支持离散列号,我观察到它的失败。
Here is the code:
这是代码:
i=10
a=1
b=0.65
if [ "$a" != "$b" ]; then
case $i in
[1]|[2]|[5]) echo "Not OK"; ;;
[9-10]|[12]) echo "may be ok"; ;;
*) echo "no clue - $i"; ;;
esac
fi
I expect this code to output may be ok
but get no clue - 10
.
我希望此代码输出may be ok
但得到no clue - 10
.
回答by Arnon Zilca
Bash case
doesn't work with numbers ranges. []
is for shell patterns.
Bashcase
不适用于数字范围。[]
用于贝壳图案。
for instance this case [1-3]5|6)
will work for 15 or 25 or 35 or 6.
例如,这种情况[1-3]5|6)
适用于 15 或 25 或 35 或 6。
Your code should look like this:
您的代码应如下所示:
i=10
a=1
b=0.65
if [ "$a" != "$b" ] ; then
case $i in
1|2|5) echo "Not OK"; ;;
9|10|12) echo "may be ok"; ;;
*) echo "no clue - $i"; ;;
esac;
fi
If i
can be real
between9 and 10 then you'll need to use if
(instead of case) with ranges.
如果i
可以real
在9 到 10之间,那么您需要使用if
(而不是大小写)范围。