我尝试使用bash,甚至尝试过文档和few threads,但我似乎无法做到正确。
S=(true false)
if (( ${S[0]} || ${S[1]} ))
then
echo "true"
else
echo "false"
fi
if
的情况下对其进行评估,即直接将其分配给变量(如果操作则不是)?答案 0 :(得分:3)
而不是S=(true false)
,您需要像这样创建数组:
S=(1 0)
然后这个if块:
if (( ${S[0]} || ${S[1]} ))
then
echo "true"
else
echo "false"
fi
将输出:
真
请注意,在BASH中,true / false被视为文字字符串“true”和“false”。
答案 1 :(得分:1)
bash中没有boolean这样的东西,只有整数算术表达式,例如((n)),如果其值大于1,将返回退出代码0(无错误或无失败代码),如果计算结果为0,则返回非零代码(具有错误代码)if
如果它调用的命令返回0退出代码,则执行then
块,否则执行else
块。你可以像这样在bash中模仿布尔系统:
#!/bin/bash
true=1
false=0
A=true
B=false
# Compare by arithmetic:
if (( A || B )); then
echo "Arithmetic condition was true."
else
echo "Arithmetic condition was false."
fi
if (( (I > 1) == true )); then ## Same as (( I > 1 )) actually.
echo "Arithmetic condition was true."
else
echo "Arithmetic condition was false."
fi
# Compare by string
if [[ $A == true || $B == true ]]; then
echo "Conditional expression was true."
else
echo "Conditional expression was false."
fi
# Compare by builtin command
if "$A" || "$B"; then
echo "True concept builtin command was called."
else
echo "False concept builtin command was called."
fi
我更喜欢字符串比较,因为尽管可能有点慢,但这种方法并不那么简单。但如果我也愿意,我也可以使用其他方法。
(( ))
,[[ ]]
,true
和false
都只是内置命令或表达式,可返回退出代码。你只是想到它们,而不是认为它们实际上是shell的主要语法的一部分。