'if
'关键字检查什么环境变量或内部的东西来决定真/假。
我有类似以下两个陈述的内容。 abc
已挂载,但 pqr
未挂载。
if mount |grep -q "abc"; then echo "export pqr"; fi
if mount |grep -q "pqr"; then echo "export abc"; fi
在上面的例子中,我希望第一个语句什么都不做,因为 abc
被挂载(所以在 mount o/p 中找到该行)因此 $?
在 mount |grep -q "abc"
为 0。
我希望第二条语句执行回显。但它正在以其他方式发生,第一个语句正在打印但第二个没有。所以想了解判断真/假的依据是什么。
Here is one related question
但该问题的公认答案是:
if [ 0 ]
is equivalent to
if [ 1 ]
如果这是真的,那么我的两个语句都应该回显,对吗?
最佳答案
您发出的命令与您从引用问题中得出的类比之间存在基本区别。
当使用 -q
选项执行 grep
时,如果找到匹配项,它会退出并返回零代码。这意味着如果 mount
的输出包含 abc
,那么
if mount |grep -q "abc"; then echo "export pqr"; fi
相当于说:
if true; then echo "export pqr"; fi
请注意,此处没有出现 test
命令,即 [
。
引自manual :
The
test
and[
builtins evaluate conditional expressions using a set of rules based on the number of arguments.0 arguments
The expression is false.
1 argument
The expression is true if and only if the argument is not null.
这解释了为什么 [ 0 ]
和 [ 1 ]
的计算结果都为真。
关于linux - shell 脚本 : How if condition evaluates true or false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24429146/