如何在Shell脚本中声明和使用布尔变量? [英] How can I declare and use Boolean variables in a shell script?

查看:554
本文介绍了如何在Shell脚本中声明和使用布尔变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I tried to declare a Boolean variable in a shell script using the following syntax:

variable=$false

variable=$true

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

Is this correct? Also, if I wanted to update that variable would I use the same syntax? Finally, is the following syntax for using Boolean variables as expressions correct?

if [ $variable ]

if [ !$variable ]

推荐答案

修订版(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内置true的评论仅适用于原始答案,而不适用于修改后的答案.

The reason the original answer is included here is because the comments before the revision on Feb 12, 2014 pertain only to the original answer, and many of the comments are wrong when associated with the revised answer. For example, Dennis Williamson's comment about bash builtin true on Jun 2, 2010 only applies to the original answer, not the revised.

这篇关于如何在Shell脚本中声明和使用布尔变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆