为什么 bash 中 `if [false]` 的计算结果为 true,而 `if false` 的计算结果却不是?

问题描述 投票:0回答:1

在 bash 中运行此脚本将打印“hello”

if [ false ]; then
    echo hello
fi

在 bash 中运行此脚本将打印“hello”

if [[ false ]]; then
    echo hello
fi

只有当我去掉括号时,bash才不会打印“hello”

if false; then
    echo hello
fi

我认为括号的整个前提是启用额外的功能,如

&&
||
,为什么在这种情况下会适得其反?

编辑: 这就是 bash 引用的意思吗?仍然打印“你好”

test=false
if [[ "$test" ]]; then
    echo hello
fi
bash shell scripting boolean sh
1个回答
0
投票
if function_or_program; then
    # do something
fi

这会检查

function_or_program
是否以
0
退出,如果退出,则执行
do something
块。

  • true
    false
    是分别以
    0
    1
    退出的程序。

  • [
    是一个程序(称为
    test
    ),可用于测试字符串和数字。

  • [[
    是一个与程序
    test
    类似的函数,但更强大,因为它是一个内置函数,调用起来可能更快。

因此,您观察到,当使用

[
[[
时,您正在测试 strings
true
false
。所有不具有长度
0
的字符串都被视为 true,因此
true
false
都将被视为
true

我认为括号的整个前提是启用额外的功能,例如

&&
||

这就是

[
[[
中的功能。
if
本身仅检查您告诉它执行的一个函数或程序的结果。

© www.soinside.com 2019 - 2024. All rights reserved.