HOWTO · Bash

在 Bash 中比较数字

这演示了使用方括号和双括号在 bash 中比较数字的不同方法

本页内容

本教程将使用方括号 [] 和双括号 - (( )) 比较 bash 中的数字。

在 Bash 中使用方括号 [] 比较数字

必须在方括号内使用比较运算符。

x=4
y=3

if [ $x -eq $y ];
then
    echo $x and $y are equal
elif [ $x -gt $y ]
then
    echo  $x is greater than $y
else
    echo  $x is less than $y
fi

输出:

4 is greater than 3

在 Bash 中使用双括号 (( )) 比较数字

必须在双括号内使用比较运算符。

x=4
y=10

if (( $x < $y ))
then
    echo $x is less than $y
elif (( $x > $y ))
then
    echo $x is greater than $y
else
    echo $x is equal to $y
fi

输出:

4 is less than 10