我尝试在shell脚本中使用以下语法声明一个布尔变量:

variable=$false

variable=$true

这对吗?另外,如果我想更新这个变量,我会使用相同的语法吗?最后,下面使用布尔变量作为表达式的语法正确吗?

if [ $variable ]

if [ !$variable ]

当前回答

以下是对miku原始答案的改进,解决了Dennis Williamson对未设置变量的情况的担忧:

the_world_is_flat=true

if ${the_world_is_flat:-false} ; then
    echo "Be careful not to fall off!"
fi

测试变量是否为false:

if ! ${the_world_is_flat:-false} ; then
    echo "Be careful not to fall off!"
fi

关于变量中有讨厌内容的其他情况,这是任何外部输入馈送到程序的问题。

任何外部输入都必须在信任它之前进行验证。但是,当接收到输入时,这种验证只需要执行一次。

它不必像Dennis Williamson建议的那样,每次使用变量都这样做,从而影响程序的性能。

其他回答

与其伪造一个布尔值,给未来的读者留下一个陷阱,为什么不使用一个比真和假更好的值呢?

例如:

build_state=success
if something-horrible; then
  build_state=failed
fi

if [[ "$build_state" == success ]]; then
  echo go home; you are done
else
  echo your head is on fire; run around in circles
fi

Bash确实将问题与[,[[,((,$((等))等混淆了。

所有人都在践踏彼此的代码空间。我想这主要是历史原因,巴什不得不偶尔装成。

大多数时候,我可以选择一种方法并坚持下去。在这种情况下,我倾向于声明(最好是在我可以包含的公共库文件中)。在我的实际脚本(s))。

TRUE=1; FALSE=0

然后我可以使用((…))算术运算符来测试。

testvar=$FALSE

if [[ -d ${does_directory_exist} ]]
then
    testvar=$TRUE;
fi

if (( testvar == TRUE )); then
    # Do stuff because the directory does exist
fi

你必须遵守纪律。你的testvar必须在任何时候都被设置为$TRUE或$FALSE。 在(……))比较器,你不需要前面的$,这使得它更可读。 我可以用(…)),因为$TRUE=1和$FALSE=0,即数值。 缺点是不得不偶尔使用$: 真正testvar = $ 这可不太好。

这不是一个完美的解决方案,但它涵盖了我需要这种测试的所有情况。

修正答案(2014年2月12日)

the_world_is_flat=true
# ...do something interesting...
if [ "$the_world_is_flat" = true ] ; then
    echo 'Be careful not to fall off!'
fi

原来的答案

警告:https://stackoverflow.com/a/21210966/89391

the_world_is_flat=true
# ...do something interesting...
if $the_world_is_flat ; then
    echo 'Be careful not to fall off!'
fi

来自:在Bash中使用布尔变量

此处包含原答案的原因是,2014年2月12日修改前的评论仅涉及原答案,许多评论与修改后的答案相关联时是错误的。例如,Dennis Williamson在2010年6月2日关于bash builtin true的评论只适用于原始答案,而不适用于修改后的答案。

我的发现和建议与其他帖子有所不同。我发现我可以像使用任何“常规”语言一样使用“布尔值”,而不需要“跳篮”……

不需要使用[]或显式的字符串比较…我尝试了多个Linux发行版。我测试了Bash、Dash和BusyBox。结果总是一样的。我不确定最初投票最多的帖子在谈论什么。也许时代变了,就是这样?

如果将一个变量设置为true,它随后会在条件中作为“肯定”进行计算。将其设置为false,它的计算结果为“负”。很简单的!唯一需要注意的是,未定义的变量的计算结果也类似于true!如果它做了相反的事情(就像在大多数语言中那样),那就好了,但这就是诀窍——你只需要显式地将你的布尔值初始化为true或false。

为什么会这样?答案是双重的。A) true/false在shell中实际上意味着“无错误”vs“错误”(即0 vs任何其他)。B) true/false不是值——而是shell脚本中的语句!关于第二点,在一行中执行true或false本身就设置了你所在块的返回值,即false是“遇到错误”的声明,而true则“清除”该值。将它与对变量的赋值一起使用,将其“返回”到变量中。一个未定义的变量在条件句中的计算结果类似于true,因为它同样表示0或“没有遇到错误”。

请参阅下面的示例Bash行和结果。如果你想确认,自己测试一下…

#!/bin/sh

# Not yet defined...
echo "when set to ${myBool}"
if ${myBool}; then echo "it evaluates to true"; else echo "it evaluates to false"; fi;

myBool=true
echo "when set to ${myBool}"
if ${myBool}; then echo "it evaluates to true"; else echo "it evaluates to false"; fi;

myBool=false
echo "when set to ${myBool}"
if ${myBool}; then echo "it evaluates to true"; else echo "it evaluates to false"; fi;

收益率

when set to
it evaluates to true
when set to true
it evaluates to true
when set to false
it evaluates to false
[[ "$x" == 'true' || "$x" -ne 0 ]] && ...

足够简单并且没有依赖项。