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

variable=$false

variable=$true

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

if [ $variable ]

if [ !$variable ]

当前回答

下面是if为true的一个实现。

# Function to test if a variable is set to "true"
_if () {
    [ "${1}" == "true" ] && return 0
    [ "${1}" == "True" ] && return 0
    [ "${1}" == "Yes" ] && return 0
    return 1
}

示例1

my_boolean=true

_if ${my_boolean} && {
    echo "True Is True"
} || {
    echo "False Is False"
}

示例2

my_boolean=false
! _if ${my_boolean} && echo "Not True is True"

其他回答

你可以使用shFlags。

它为您提供了定义:DEFINE_bool的选项

例子:

DEFINE_bool(big_menu, true, "Include 'advanced' options in the menu listing");

在命令行中你可以定义:

sh script.sh --bigmenu
sh script.sh --nobigmenu # False

修正答案(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的评论只适用于原始答案,而不适用于修改后的答案。

替代-使用函数

is_ok(){ :;}
is_ok(){ return 1;}
is_ok && echo "It's OK" || echo "Something's wrong"

定义函数不那么直观,但是检查它的返回值非常容易。

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

例如:

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
[[ "$x" == 'true' || "$x" -ne 0 ]] && ...

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