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

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

问题描述

我试着用下面的语法来声明在shell脚本中的布尔变量:

 变量= $假变量= $真

这是正确的?另外,如果我想更新变量将我使用相同的语法?最后,是使用布尔变量前pressions正确的语法如下:

 如果[$变量]如果[!$变量]


解决方案

修订答(2014年2月12日)

  the_world_is_flat = TRUE
#...做一些有趣的事情...
如果[$ the_world_is_flat=真];然后
    呼应小心别掉下来!
科幻


原来的答案

注意事项: http://stackoverflow.com/a/21210966/89391

  the_world_is_flat = TRUE
#...做一些有趣的事情...
如果$ the_world_is_flat;然后
    呼应小心别掉下来!
科幻

从:<一href=\"https://github.com/aperezdc/perezdecastro.org/blob/master/stash/using-boolean-variables-in-bash.markdown\">Using Bash中布尔变量

原来答案就在这里包含的原因是因为在2014年2月12日改版前的注释只涉及到原来的答案,许多意见时修订相关答案是错的。例如,丹尼斯·威廉姆森的有关评论bash的内置真正在2010年6月2日仅适用于原来的答案,而不是修改。

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


Original Answer

Caveats: http://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

From: Using boolean variables in Bash

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