Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
371 views
in Technique[技术] by (71.8m points)

shell - How can I compare numbers in Bash?

I'm unable to get numeric comparisons working:

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 is that it compares the number from the first digit on, i.e., 9 is bigger than 10, but 1 is greater than 09.

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

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In Bash, you should do your check in an arithmetic context:

if (( a > b )); then
    ...
fi

For POSIX shells that don't support (()), you can use -lt and -gt.

if [ "$a" -gt "$b" ]; then
    ...
fi

You can get a full list of comparison operators with help test or man test.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...