2017-09-03 69 views
0

我编写了这个脚本来比较bash中的2个数字,但它给了我一些数字的错误答案。 一样,如果我给它2 & 2输入,它给了我 “X大于Y”比较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 
+0

对于比较数字,使用''为>','-lt' -gt'运营商'<'和'-eq'为'=' – anubhava

+0

@anubhava但输入“2和3”却给出了错误的答案 – Kiana

回答

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

你可以使用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 
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为<,==为=)

+0

关于最后一行:no,在''[']'中使用'-eq'来表示数值相等,而不是'=='。 – Kusalananda

0

要尽可能少地进行更改,使括号加倍 - 输入'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