简体   繁体   中英

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:

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

-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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM