简体   繁体   中英

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 

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 

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.

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

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 

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