Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing numbers in bash scripting

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 
like image 418
Keipro Avatar asked Sep 12 '25 02:09

Keipro


1 Answers

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 
like image 106
ifma Avatar answered Sep 14 '25 15:09

ifma