如何在 Bash 中比较数字? [英] How can I compare numbers in Bash?

查看:42
本文介绍了如何在 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 an 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 testman test 获取比较运算符的完整列表.

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

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

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