在bash比较数字 [英] Comparing numbers in bash

查看:130
本文介绍了在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. I'm sure this is very basic to many of you I just can't seem to find the answer to my question anywhere (or at least I'm not totally sure what to search for). 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;

我的问题是,它的数目,从所述第一数字进行比较,即,图9是大于10000大,但1大于09如何可以转换的数字成型做一个真比较?我意识到,这可能是不快简单,但任何帮助将大大AP preciated!

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? I realise that this is probably irritatingly simple, but any help would be greatly appreciated!

推荐答案

在bash中,你应该做你的支票算术上下文

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

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

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

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

您可以得到比较运营商的完整列表,以帮助测试

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

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

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