小编典典

如何在 shell 脚本中声明和使用布尔变量?

all

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

variable=$false

variable=$true

它是否正确?另外,如果我想更新该变量,我会使用相同的语法吗?最后,以下使用布尔变量作为表达式的语法是否正确?

if [ $variable ]

if [ !$variable ]

阅读 155

收藏
2022-02-25

共1个答案

小编典典

修订后的答案(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 Williamsontrue在 2010 年 6 月 2 日对内置 bash 的评论仅适用于原始答案,而不适用于修订后的答案。

2022-02-25