Home > Software design >  Comparing numbers using Bash
Comparing numbers using Bash

Time:06-18

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:

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

CodePudding user response:

-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
  • Related