Comparing numbers in Bash

2018-12-31 14:38发布

I'm starting to learn about writing scripts for the bash terminal, but I can't work out how to get the comparisons to work properly. The script I'm using is:

echo "enter two numbers";
read a b;

echo "a=$a";
echo "b=$b";

if [ $a \> $b ];
then 
    echo "a is greater than b";
else
    echo "b is greater than a";
fi;

The problem I have is that it compares the number from the first digit on, i.e. 9 is bigger than 10000, but 1 is greater than 09

How can I convert the numbers into a type to do a true comparison?

7条回答
回忆,回不去的记忆
2楼-- · 2018-12-31 15:31

If you have floats you can write a function and then use that e.g.

#!/bin/bash

function float_gt() {
    perl -e "{if($1>$2){print 1} else {print 0}}"
}

x=3.14
y=5.20
if [ $(float_gt $x $y) == 1 ] ; then
    echo "do stuff with x"
else
    echo "do stuff with y"
fi
查看更多
登录 后发表回答