如何比较bash中的数字? [英] How to compare numbers in bash?

查看:53
本文介绍了如何比较bash中的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法进行数字比较:

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;

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

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?

推荐答案

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

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

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

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

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

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

您可以通过 help test man test 获得比较运算符的完整列表.

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

这篇关于如何比较bash中的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆