ten*_*les 129 bash conditional-operator
本周一直在学习bash并陷入困境.
#!/bin/sh
if [ false ]; then
echo "True"
else
echo "False"
fi
Run Code Online (Sandbox Code Playgroud)
这将始终输出True,即使条件似乎表示不是这样.如果我删除括号[]然后它工作,但我不明白为什么.
che*_*ner 163
您正在使用参数"false" 运行[(aka test)命令,而不是运行该命令false.由于"false"是非空字符串,因此test命令始终成功.要实际运行该命令,请删除该[命令.
if false; then
echo "True"
else
echo "False"
fi
Run Code Online (Sandbox Code Playgroud)
Bee*_*jor 42
该if声明需要一个命令作为参数(如做&&,||等).该命令的整数结果代码被解释为布尔值(0/null = true,1/else = false).
该test语句将运算符和操作数作为参数,并以与格式相同的格式返回结果代码if.该test语句的别名,[通常用于if执行更复杂的比较.
该true和false语句什么也不做,返回的结果代码(0和1,分别).所以它们可以在Bash中用作布尔文字.但是如果你把语句放在一个被解释为字符串的地方,你就会遇到问题.在你的情况下:
if [ foo ]; then ... # "if the string 'foo' is non-empty, return true"
if foo; then ... # "if the command foo succeeds, return true"
Run Code Online (Sandbox Code Playgroud)
所以:
if [ true ] ; then echo "This text will always appear." ; fi;
if [ false ] ; then echo "This text will always appear." ; fi;
if true ; then echo "This text will always appear." ; fi;
if false ; then echo "This text will never appear." ; fi;
Run Code Online (Sandbox Code Playgroud)
这类似于做类似echo '$foo'对战echo "$foo".
使用该test语句时,结果取决于使用的运算符.
if [ "$foo" = "$bar" ] # true if the string values of $foo and $bar are equal
if [ "$foo" -eq "$bar" ] # true if the integer values of $foo and $bar are equal
if [ -f "$foo" ] # true if $foo is a file that exists (by path)
if [ "$foo" ] # true if $foo evaluates to a non-empty string
if foo # true if foo, as a command/subroutine,
# evaluates to true/success (returns 0 or null)
Run Code Online (Sandbox Code Playgroud)
简而言之,如果您只想测试通过/失败(也称为"true"/"false"),则将命令传递给您if或&&等语句,不带括号.对于复杂的比较,请使用括号和适当的运算符.
是的,我知道在Bash中没有本地布尔类型if,[而且true在技术上是"命令"而不是"语句"; 这只是一个非常基本的功能性解释.
小智 7
我发现我可以通过运行以下命令来执行一些基本逻辑:
A=true
B=true
if ($A && $B); then
C=true
else
C=false
fi
echo $C
Run Code Online (Sandbox Code Playgroud)