比较bash脚本中的数字

时间:2017-09-03 07:26:30

标签: linux bash shell terminal

我写了这个脚本来比较bash中的2个数字但它给了我一些数字的错误答案。 就像我给它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 

4 个答案:

答案 0 :(得分:2)

您可以尝试使用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 

答案 1 :(得分:1)

这对我有用:

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,我建议您使用[[ ... ]]代替[ ... ]括号。

答案 2 :(得分: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运算符代表&gt;, - lt代表&lt;,== for =)

答案 3 :(得分:0)

尽可能少地更改括号 - 进入'double bracket'模式(仅在Bash shell中的bash / zsh中有效)。

如果您希望与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