Bash 中单方括号和双方括号的区别

Fumbani Banda 2023年1月30日 Bash
  1. Bash 中的单方括号 [ ]
  2. Bash 中的双方括号 [[ ]]
  3. Bash 中单方括号和双方括号的区别
Bash 中单方括号和双方括号的区别

本教程解释了 Bash 中的单方括号和双方括号及其区别。

Bash 中的单方括号 [ ]

单方括号 [ 是 Bash shell 中 test 命令的另一个名称。test 命令是所有 POSIX shell 中的标准实用程序。 ][ 的最后一个参数。

下面的两个脚本表明 [test 命令是相似的。第一个脚本使用单方括号检查变量 $y 中的值是否大于变量 $x 中的值并根据 test 命令中的评估返回的结果打印输出.

在我们的例子中,$y 变量的值大于 $x 变量的值。

#!/bin/bash

x=2
y=3

if [ $y -gt $x ]
then
    echo "$y is greater than $x"
else
    echo "$x is greater than $y"
fi

该脚本在执行时将以下消息打印到标准输出。

3 is greater than 2

该脚本使用 test 命令而不是单个方括号。该脚本检查 $y 变量中的值是否大于 $x 变量中的值。

如果 test 返回 true,脚本执行第一个 echo 命令,如果 test 返回 false,它执行 else 部分中的 echo 命令。

在我们的例子中,$y 变量的值比 $x 变量 2 大 3。脚本将执行第一个 echo 命令。

#!/bin/bash

x=2
y=3

if test $y -gt $x
then
    echo "$y is greater than $x"
else
    echo "$x is greater than $y"
fi

该脚本将以下输出打印到标准输出。

3 is greater than 2

Bash 中的双方括号 [[ ]]

双方括号 [[]] 扩展了从 ksh88 采用的 test 命令;它更加通用。双方括号可用于模式匹配、参数扩展,它们不允许分词。

使用双方括号有助于避免 Bash 脚本中的逻辑错误。在双方括号中,&&||<> 运算符在 test 命令中给出错误时起作用。

我们在下面的脚本中使用方括号进行算术评估。双方括号测试 $x 变量中的值是否等于 $y 变量中的值。

测试返回 true 并执行脚本中的第一个 echo 命令。

#!/bin/bash

x=10
y=10

if [[ $x -eq $y ]]
then
    echo "\$x is equal to \$y"
else
    echo "\$x is not equal to \$y"
fi

运行脚本会在标准终端中产生以下输出。

$x is equal to $y

Bash 中单方括号和双方括号的区别

test 命令是标准 POSIX shell 上的内置 Bash 实用程序,而双方括号不是命令。双方括号是 Bash 中的扩展,改编自用作关键字的 ksh88

test 命令相比,双方括号支持更多功能。与 test 命令不同,它支持模式匹配和参数扩展,并且不允许分词。

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Fumbani Banda
Fumbani Banda avatar Fumbani Banda avatar

Fumbani is a tech enthusiast. He enjoys writing on Linux and Python as well as contributing to open-source projects.

LinkedIn GitHub