Keipro
Keipro

Reputation: 107

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 

Upvotes: 4

Views: 14923

Answers (4)

slavik
slavik

Reputation: 1303

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 

Upvotes: 1

Tanmay
Tanmay

Reputation: 111

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

Upvotes: 0

ifma
ifma

Reputation: 3818

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 

Upvotes: 7

anubhava
anubhava

Reputation: 785156

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.

Upvotes: 4

Related Questions