Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

bash - 在Bash中比较数字(Comparing numbers in Bash)

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.

(我开始学习有关为bash终端编写脚本的知识,但是我无法弄清楚如何使比较正常工作。)

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

(问题在于,它会比较从第一个数字开始的数字,即9大于10,但1大于09。)

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

(如何将数字转换为类型以进行真正的比较?)

  ask by advert2013 translate from so

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

1 Reply

0 votes
by (71.8m points)

In bash, you should do your check in arithmetic context :

(在bash中,您应该在算术上下文中进行检查:)

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

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

(对于不支持(()) POSIX shell,可以使用-lt-gt 。)

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

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

(您可以通过help test获得比较运算符的完整列表。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...