Bash 中的嵌套条件(if [[...)
我有几个问题想要得到解答,因为到目前为止我还不是 Bash 专家...在执行特定任务之前我需要检查几个条件,但其中一些是相关的并且不能分离:我会就像下面要检查的语句:
if ((1 OR 2) AND (3 OR 4))
then
blabla...
fi
到目前为止我已经做到了,
if [[ "[ `echo "$5" | cut -c 1-2` -lt 0 || `echo "$5" | cut -c 1-2` -gt 23 ]" && "[ `echo "$5" | cut -c 4-5` -lt 0 || `echo "$5" | cut -c 4-5` -gt 23 ]" ]]
then
echo "La plage horaire indiquée n'est pas valide ! Format = HH-HH"
exit 3
fi
并且它工作正常。我有一种感觉,为了执行此检查,可以做一些更容易的事情,但我看不出如何...
第二件事,在我上面编写的代码中,您可以看到这一点:
"[ `echo "$5" | cut -c 1-2` -lt 0 || `echo "$5" | cut -c 1-2` -gt 23 ]"
简单的方括号对应到测试功能,对吗?那么为什么在加上双引号时它会被正确调用呢?我知道我不能在那里放任何反引号,它对我的 echo "$5"... 没有任何意义,但是双引号应该替换特殊字符,例如 $ 并防止忽略单个空格,那么为什么是它取代了 [ 字符?它被视为这些特殊字符之一吗?
预先感谢您的回答!
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 :
if ((1 OR 2) AND (3 OR 4))
then
blabla...
fi
I made this so far,
if [[ "[ `echo "$5" | cut -c 1-2` -lt 0 || `echo "$5" | cut -c 1-2` -gt 23 ]" && "[ `echo "$5" | cut -c 4-5` -lt 0 || `echo "$5" | 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 "$5" | cut -c 1-2` -lt 0 || `echo "$5" | 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 ?
Thank you in advance for your answers !
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
来自
帮助[[
:From
help [[
:不要重复自己:
或者使用bash参数扩展语法:
并且您可以使用算术替换:
Don't repeat yourself:
or use bash parameter expansion syntax:
And you can use arithmetic substitution: