Bash 中的嵌套条件(如果 [[...]
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5909811/
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
Nested conditions in Bash (if [[...)
提问by SonicGold
I have several questions I would like to be answered since I'm not a Bash expert so far... There are several conditions I need to check before performing a specific task, but some of them are related and cannot be detached : I would like the following statement to be checked :
我有几个问题想要回答,因为到目前为止我还不是 Bash 专家......在执行特定任务之前我需要检查几个条件,但其中一些是相关的并且无法分离:我会像下面要检查的语句:
if ((1 OR 2) AND (3 OR 4))
then
blabla...
fi
I made this so far,
到目前为止,我做了这个,
if [[ "[ `echo "" | cut -c 1-2` -lt 0 || `echo "" | cut -c 1-2` -gt 23 ]" && "[ `echo "" | cut -c 4-5` -lt 0 || `echo "" | cut -c 4-5` -gt 23 ]" ]]
then
echo "La plage horaire indiquée n'est pas valide ! Format = HH-HH"
exit 3
fi
and it works properly. I have the feeling that there's something much easier that can be done in order to perform this check, but I cannot see how...
它工作正常。我有一种感觉,为了执行这项检查,可以做一些更容易的事情,但我看不出如何......
And second thing, in the code I wrote above, you can see this :
第二件事,在我上面写的代码中,你可以看到:
"[ `echo "" | cut -c 1-2` -lt 0 || `echo "" | cut -c 1-2` -gt 23 ]"
The simple square-bracket corresponds to the test function, right ? So why is it properly called when putting double-quotes ? I understand I could not put any backquote there, it would not make any sense with my echo "$5"... thing, but double-quotes are supposed to replace special characters such as $ and prevent from ignoring single spaces, so why is it replacing the [ character ? Is it considered as one of these special characters ?
简单的方括号对应于测试函数,对吗?那么为什么在放置双引号时正确调用它呢?我知道我不能在那里放任何反引号,这对我的 echo "$5"... 没有任何意义,但是双引号应该替换特殊字符,例如 $ 并防止忽略单个空格,那么为什么它取代了 [ 字符 ? 它是否被视为这些特殊字符之一?
Thank you in advance for your answers !
预先感谢您的回答!
回答by glenn Hymanman
Don't repeat yourself:
不要重复自己:
a=$(echo "" | cut -c 1-2)
b=$(echo "" | cut -c 4-5)
or use bash parameter expansion syntax:
或使用 bash 参数扩展语法:
a=${5:0:2}
b=%{5:3:2}
And you can use arithmetic substitution:
您可以使用算术替换:
if (( a < 0 || a > 23)) && (( b < 0 || b > 23 )); then
echo "La plage horaire indiquée n'est pas valide ! Format = HH-HH"
exit 3
fi
回答by Ignacio Vazquez-Abrams
From help [[:
来自help [[:
( EXPRESSION ) Returns the value of EXPRESSION
( EXPRESSION ) Returns the value of EXPRESSION

