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

variable=$false

variable=$true

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

if [ $variable ]

if [ !$variable ]

当前回答

与其伪造一个布尔值,给未来的读者留下一个陷阱,为什么不使用一个比真和假更好的值呢?

例如:

build_state=success
if something-horrible; then
  build_state=failed
fi

if [[ "$build_state" == success ]]; then
  echo go home; you are done
else
  echo your head is on fire; run around in circles
fi

其他回答

下面是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"
[[ "$x" == 'true' || "$x" -ne 0 ]] && ...

足够简单并且没有依赖项。

与其伪造一个布尔值,给未来的读者留下一个陷阱,为什么不使用一个比真和假更好的值呢?

例如:

build_state=success
if something-horrible; then
  build_state=failed
fi

if [[ "$build_state" == success ]]; then
  echo go home; you are done
else
  echo your head is on fire; run around in circles
fi

这是一个关于在Bash中测试“布尔”值的不同方法的速度测试:

#!/bin/bash
rounds=100000

b=true # For true; b=false for false
type -a true
time for i in $(seq $rounds); do command $b; done
time for i in $(seq $rounds); do $b; done
time for i in $(seq $rounds); do [ "$b" == true ]; done
time for i in $(seq $rounds); do test "$b" == true; done
time for i in $(seq $rounds); do [[ $b == true ]]; done

b=x; # Or any non-null string for true; b='' for false
time for i in $(seq $rounds); do [ "$b" ]; done
time for i in $(seq $rounds); do [[ $b ]]; done

b=1 # Or any non-zero integer for true; b=0 for false
time for i in $(seq $rounds); do ((b)); done

它会打印出

true is a shell builtin
true is /bin/true

real    0m0,815s
user    0m0,767s
sys     0m0,029s

real    0m0,562s
user    0m0,509s
sys     0m0,022s

real    0m0,829s
user    0m0,782s
sys     0m0,008s

real    0m0,782s
user    0m0,730s
sys     0m0,015s

real    0m0,402s
user    0m0,391s
sys     0m0,006s

real    0m0,668s
user    0m0,633s
sys     0m0,008s

real    0m0,344s
user    0m0,311s
sys     0m0,016s

real    0m0,367s
user    0m0,347s
sys     0m0,017s

很久以前,当我们只有sh时,布尔值依赖于测试程序的约定来处理,在测试程序中,如果运行时不带任何参数,则返回错误的退出状态。

这允许人们认为一个未设置为false的变量和设置为任何值的变量为true。今天,test是Bash内置的,通常以它的一个字符别名[(或者在没有它的shell中使用的可执行文件,如dolmen所述)而为人所知:

FLAG="up or <set>"

if [ "$FLAG" ] ; then
    echo 'Is true'
else
    echo 'Is false'
fi

# Unset FLAG
#    also works
FLAG=

if [ "$FLAG" ] ; then
    echo 'Continues true'
else
    echo 'Turned false'
fi

由于引号的约定,脚本作者更喜欢使用复合命令[[,它模仿test,但具有更好的语法:带空格的变量不需要被引用;可以使用&&和||作为具有奇怪优先级的逻辑运算符,并且没有POSIX对术语数量的限制。

例如,要确定是否设置了FLAG并且COUNT是一个大于1的数字:

FLAG="u p"
COUNT=3

if [[ $FLAG  && $COUNT -gt '1' ]] ; then
    echo 'Flag up, count bigger than 1'
else
    echo 'Nope'
fi

当空格、零长度字符串和空变量都需要时,或者当脚本需要使用多个shell时,这些东西可能会令人困惑。