shell脚本中的布尔变量

时间:2017-07-12 13:05:41

标签: shell boolean logical-operators

我关注这篇文章 How to declare and use boolean variables in shell script?

并开发了一个简单的shell脚本

#!/bin/sh                                                                                                                                                                                                   
a=false
if [[ $a ]];
then
    echo "a is true"
else
    echo "a is false"
fi

输出

a is true

有什么问题?

3 个答案:

答案 0 :(得分:1)

您需要检查值是否等于{{1}},而不仅仅是变量是否设置。请尝试以下方法:

{{1}}

答案 1 :(得分:1)

这不起作用,因为[[仅测试变量是否为空。
你需要写:

if [[ $a = true ]];

而不仅仅是

if [[ $a ]];

答案 2 :(得分:1)

请注意,truefalse实际上是在bash中内置命令,因此您可以省略条件括号,只需执行以下操作:

<击>
if $a; 

<击>

阅读this excellent answer后,

更新:,我撤消了这条建议。

if [[ $a ]]无法正常工作的原因是当[[命令只接收一个参数时(除了结束]]),返回值为成功这个论点是非空的。显然字符串“false”不是空字符串。请参阅https://www.gnu.org/software/bash/manual/bashref.html#Conditional-Constructshttps://www.gnu.org/software/bash/manual/bashref.html#Bash-Conditional-Expressions