Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Comparing numbers using Bash

I wrote a script to compare two numbers:

#!/bin/bash

read X
read Y

if [[ $X -le $Y ]]; 
then 
    echo "X is less than Y"

elif [[ $X -ge $Y ]]; 
then
    echo "X is greater than Y"

else 
    echo "X is equal to Y"
fi

For some reason when the value of X and Y are the same, the else condition is not executed. Instead the if [[ $X -le $Y ]]; is executed.

When I change the position of the if and else conditions:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#!/bin/bash

read X
read Y

if [[ $X -eq $Y ]]; 
then 
    echo "X is equal to Y"

elif [[ $X -ge $Y ]]; 
then
    echo "X is greater than Y"

else 
    echo "X is less than Y"
fi

The else condition is executed for this case. Can someone please give me an explanation to why the else condition is executed for one case but not the other?

>Solution :

-le and -ge are like <= and >=.

  • -le = less than or equal
  • -ge = greater than or equal
  • -lt = less than
  • -gt = greater than

It’ll work if you switch to -lt and -gt:

if [[ $X -lt $Y ]]
then 
    echo "X is less than Y"

elif [[ $X -gt $Y ]]
then
    echo "X is greater than Y"

else 
    echo "X is equal to Y"
fi

You can also use (( )) for arithmetic operations. It has more natural syntax: you can use < and >, you don’t need spaces around the operators, and $ dollar signs are optional.

if ((X < Y))
then 
    echo "X is less than Y"

elif ((X > Y))
then
    echo "X is greater than Y"

else 
    echo "X is equal to Y"
fi
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading