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

查看:45
本文介绍了如何在 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 ]

推荐答案

Revised Answer (Feb 12, 2014)

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

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天全站免登陆