在Bash脚本中比较数字

3

我写了一个bash脚本来比较两个数字,但是对于一些数字它给出了错误的答案。 例如,如果我输入2&2,它会给我返回"X大于Y"。

#!/bin/bash 
read num1
read num2
if [ $num1 > $num2 ]
    then 
        echo "X is greater than Y"
elif [ $num1 < $num2 ]
    then 
        echo "X is less than Y"
elif [ $num1 = $num2 ]
    then 
        echo "X is equal to Y"
fi 

比较数字时,使用 -gt 操作符表示 >,使用 -lt 表示 <,使用 -eq 表示 = - anubhava
@anubhava但对于输入“2 and 3”,它给出了错误的答案。 - Keipro
可能是在Bash中比较数字的重复问题。 - jww
4个回答

6

您可以尝试使用Bash算术环境:

#!/bin/bash 
read num1
read num2
if (( num1 > num2 ))
    then 
        echo "X is greater than Y"
elif (( num1 < num2 ))
    then 
        echo "X is less than Y"
elif (( num1 == num2 ))
    then 
        echo "X is equal to Y"
fi 

4
这对我很有效:
cmp() {
    num1="$1"
    num2="$2"

    if [ $num1 -gt $num2 ]
        then 
            echo "X is greater than Y"
    elif [ $num1 -lt $num2 ]
        then 
            echo "X is less than Y"
    elif [ $num1 -eq $num2 ]
        then 
            echo "X is equal to Y"
    fi
}

然后查看结果:
cmp 2 3
X is less than Y

cmp 2 2
X is equal to Y

cmp 2 1
X is greater than Y

由于您正在使用 bash,我建议您使用 [[ ... ]] 括号而不是 [ ... ] 括号。


1

为了尽可能少地进行更改,请将括号加倍 - 进入'double bracket'模式(仅适用于bash/zsh而不是Bourne shell)。

如果您想与sh兼容,可以保持'single bracket'模式,但需要替换所有运算符。

'single bracket'模式下,运算符如'<','>', '='仅用于比较字符串。要在'single bracket'模式下比较数字,您需要使用'-gt''-lt''-eq'

#!/bin/bash 
read num1
read num2
if [[ $num1 > $num2 ]]
    then 
        echo "X is greater than Y"
elif [[ $num1 < $num2 ]]
    then 
        echo "X is less than Y"
elif [[ $num1 = $num2 ]]
    then 
        echo "X is equal to Y"
fi 

我认为在Bash中应该使用单个'['。同时使用-gt,否则这将会给出错误的输出。 - Melroy van den Berg

0
#!/bin/sh

echo hi enter first  number
read num1 

echo hi again enter second number
read num2

if [ "$num1" -gt "$num2" ]
then
  echo $num1 is greater than $num2
elif [ "$num2" -gt "$num1" ]
then
  echo $num2 is greater than $num1
else
  echo $num1 is equal to $num2
fi

请注意:我们将使用-gt运算符表示>,-lt表示<,==表示=。

关于最后一行:不,你在 [ ... ] 中使用 -eq 表示数字相等,而不是 == - Kusalananda

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接