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

variable=$false

variable=$true

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

if [ $variable ]

if [ !$variable ]

当前回答

在许多编程语言中,布尔类型是或被实现为整数的子类型,其中true表现为1,false表现为0:

C语言中的布尔值 Python中的布尔值 Java中的布尔值

数学上,布尔代数类似于整数模数2。因此,如果一种语言不提供本机布尔类型,最自然和有效的解决方案是使用整数。这几乎适用于任何语言。例如,在Bash中,你可以这样做:

# val=1; ((val)) && echo "true" || echo "false"
true
# val=0; ((val)) && echo "true" || echo "false"
false

男人bash:

(表达) 表达式根据下面算术求值部分描述的规则求值。如果表达式的值非0,则返回状态为0;否则返回状态为1。这完全等价于let“expression”。

其他回答

下面是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

博士TL;

my_bool=true

if [ "$my_bool" = true ]

未来音乐(最初)的回答有问题

我不推荐公认的答案。它的语法很漂亮,但也有一些缺陷。

假设我们有以下条件。

if $var; then
  echo 'Muahahaha!'
fi

在以下情况2中,此条件将计算为true并执行嵌套命令。

# Variable var not defined beforehand. Case 1
var=''  # Equivalent to var="".      # Case 2
var=                                 # Case 3
unset var                            # Case 4
var='<some valid command>'           # Case 5

通常,当你的“布尔”变量var显式设置为true时,你只希望你的条件值为true。其他所有的案例都是危险的误导!

最后一种情况(#5)特别淘气,因为它将执行变量中包含的命令(这就是为什么对于有效的command3,4,条件的计算结果为true)。

这里有一个无害的例子:

var='echo this text will be displayed when the condition is evaluated'
if $var; then
  echo 'Muahahaha!'
fi

# Outputs:
# this text will be displayed when the condition is evaluated
# Muahahaha!

引用你的变量是更安全的,例如,if "$var";然后。在上述情况下,您应该得到一个警告,表示没有找到该命令。但我们仍然可以做得更好(见下面我的建议)。

也可以看看Mike Holt对Miku最初答案的解释。

赫巴的回答有问题

这种方法也有意想不到的行为。

var=false
if [ $var ]; then
  echo "This won't print, var is false!"
fi

# Outputs:
# This won't print, var is false!

您可能期望上述条件的值为false,因此永远不会执行嵌套语句。惊喜!

引用值("false"),引用变量("$var"),或者使用test或[[而不是[,都没有区别。

我的建议是:

以下是我建议你检查“布尔值”的方法。他们按照预期工作。

my_bool=true

if [ "$my_bool" = true ]; then
if [ "$my_bool" = "true" ]; then

if [[ "$my_bool" = true ]]; then
if [[ "$my_bool" = "true" ]]; then
if [[ "$my_bool" == true ]]; then
if [[ "$my_bool" == "true" ]]; then

if test "$my_bool" = true; then
if test "$my_bool" = "true"; then

它们几乎都是一样的。与其他答案5中的方法相比,您将不得不输入更多的按键,但您的代码将更具防御性。


脚注

未来音乐的回答已被编辑,不再包含(已知的)缺陷。 这不是一个详尽的清单。 在此上下文中,有效命令是指存在的命令。命令使用正确或不正确并不重要。例如,man woman仍然被认为是一个有效的命令,即使没有这样的手册页存在。 对于无效的(不存在的)命令,Bash只会报错说没有找到该命令。 如果你关心长度,第一个建议是最短的。

使用算术表达式。

#!/bin/bash

false=0
true=1

((false)) && echo false
((true)) && echo true
((!false)) && echo not false
((!true)) && echo not true

输出:

真正的 不是假的

Bill Parker被否决了,因为他的定义与正常的代码约定相反。通常,true被定义为0,false被定义为非0。1对false有效,9999和-1也一样。函数的返回值也是一样——0表示成功,任何非0表示失败。对不起,我还没有足够的街头信誉来投票或直接回复他。

Bash建议现在使用双括号而不是单括号作为一种习惯,Mike Holt给出的链接解释了它们工作方式的差异。7.3. 其他比较操作符

首先,-eq是一个数值运算符,所以有代码

#**** NOTE *** This gives error message *****
The_world_is_flat=0;
if [ "${The_world_is_flat}" -eq true ]; then

将发出错误语句,期望得到整数表达式。这适用于任意一个参数,因为两者都不是整数值。然而,如果我们在它周围加上双括号,它将不会发出错误声明,但它将产生一个错误的值(好吧,在50%的可能排列中)。它将计算为[[0 -eq true]] = success,但也计算为[[0 -eq false]] = success,这是错误的(嗯,....如果这个内置是一个数值呢?)

#**** NOTE *** This gives wrong output *****
The_world_is_flat=true;
if [[ "${The_world_is_flat}" -eq true ]]; then

还有其他的条件排列也会给出错误的输出。基本上,将一个变量设置为数值并将其与一个真/假的内置变量进行比较,或者将一个变量设置为真/假的内置变量并将其与一个数值进行比较的任何事情(上面列出的错误条件除外)。此外,任何将一个变量设置为true/false的内置变量,并使用-eq进行比较。所以避免使用-eq进行布尔比较,避免使用数值进行布尔比较。下面是会产生无效结果的排列的总结:

# With variable set as an integer and evaluating to true/false
# *** This will issue error warning and not run: *****
The_world_is_flat=0;
if [ "${The_world_is_flat}" -eq true ]; then

# With variable set as an integer and evaluating to true/false
# *** These statements will not evaluate properly: *****
The_world_is_flat=0;
if [ "${The_world_is_flat}" -eq true ]; then
#
if [[ "${The_world_is_flat}" -eq true ]]; then
#
if [ "${The_world_is_flat}" = true ]; then
#
if [[ "${The_world_is_flat}" = true ]]; then
#
if [ "${The_world_is_flat}" == true ]; then
#
if [[ "${The_world_is_flat}" == true ]]; then


# With variable set as an true/false builtin and evaluating to true/false
# *** These statements will not evaluate properly: *****
The_world_is_flat=true;
if [[ "${The_world_is_flat}" -eq true ]]; then
#
if [ "${The_world_is_flat}" = 0 ]; then
#
if [[ "${The_world_is_flat}" = 0 ]]; then
#
if [ "${The_world_is_flat}" == 0 ]; then
#
if [[ "${The_world_is_flat}" == 0 ]]; then

那么,现在来看看什么是有效的。在比较和计算时使用真/假内置参数(Mike Hunt指出,不要用引号括起来)。然后使用一个或一个或两个等号(=或==)和一个或两个括号([]或[[]])。就我个人而言,我喜欢双等号,因为它让我想起了其他编程语言中的逻辑比较,而双引号只是因为我喜欢打字。所以这些工作:

# With variable set as an integer and evaluating to true/false
# *** These statements will work properly: *****
#
The_world_is_flat=true/false;
if [ "${The_world_is_flat}" = true ]; then
#
if [[ "${The_world_is_flat}" = true ]]; then
#
if [ "${The_world_is_flat}" = true ]; then
#
if [[ "${The_world_is_flat}" == true ]]; then

你知道了。