Comparing numbers in bash scripting

与世无争的帅哥 提交于 2020-01-14 05:17:07

问题


I wrote this script to compare 2 numbers in bash but it gives me wrong answers for some numbers. like if I give it 2&2 for input , it gives me "X is greater than 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 

回答1:


You can try with bash arithmetic contexts:

#!/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 



回答2:


This works for me:

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
}

Then see the results:

cmp 2 3
X is less than Y

cmp 2 2
X is equal to Y

cmp 2 1
X is greater than Y

Since you're using bash, I suggest you to use [[ ... ]] instead of [ ... ] brackets.




回答3:


#!/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

(Please note : we will use -gt operator for > , -lt for < , == for = )




回答4:


To make as few changes as possible double the brackets - to enter 'double bracket' mode (is only valid in bash/zsh not in Bourne shell).

If you want to be compatible with sh you can stay in 'single bracket' mode but you need to replace all operators.

In 'single bracket' mode operators like '<','>', '=' are used only to compare strings. To compare numbers in 'single bracket' mode you need to use '-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 


来源:https://stackoverflow.com/questions/46021194/comparing-numbers-in-bash-scripting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!