简体   繁体   English

在bash脚本中比较数字

[英]Comparing numbers in bash scripting

I wrote this script to compare 2 numbers in bash but it gives me wrong answers for some numbers. 我编写此脚本的目的是比较bash中的2个数字,但对于某些数字却给出了错误的答案。 like if I give it 2&2 for input , it gives me "X is greater than Y" 就像我给它2&2作为输入一样,它给我“ X大于Y”

#!/bin/bash 
read num1
read num2
if [ $num1 > $num2 ]
    then 
        echo "X is greater than Y"
elif [ $num1 < $num2 ]
    then 
        echo "X is less than Y"
elif [ $num1 = $num2 ]
    then 
        echo "X is equal to Y"
fi 

You can try with bash arithmetic contexts: 您可以尝试使用bash算术上下文:

#!/bin/bash 
read num1
read num2
if (( num1 > num2 ))
    then 
        echo "X is greater than Y"
elif (( num1 < num2 ))
    then 
        echo "X is less than Y"
elif (( num1 == num2 ))
    then 
        echo "X is equal to Y"
fi 

This works for me: 这对我有用:

cmp() {
    num1="$1"
    num2="$2"

    if [ $num1 -gt $num2 ]
        then 
            echo "X is greater than Y"
    elif [ $num1 -lt $num2 ]
        then 
            echo "X is less than Y"
    elif [ $num1 -eq $num2 ]
        then 
            echo "X is equal to Y"
    fi
}

Then see the results: 然后查看结果:

cmp 2 3
X is less than Y

cmp 2 2
X is equal to Y

cmp 2 1
X is greater than Y

Since you're using bash , I suggest you to use [[ ... ]] instead of [ ... ] brackets. 由于您使用的是bash ,因此建议您使用[[ ... ]]而不是[ ... ]方括号。

#!/bin/sh

echo hi enter first  number
read num1 

echo hi again enter second number
read num2

if [ "$num1" -gt "$num2" ]
then
  echo $num1 is greater than $num2
elif [ "$num2" -gt "$num1" ]
then
  echo $num2 is greater than $num1
else
  echo $num1 is equal to $num2
fi

(Please note : we will use -gt operator for > , -lt for < , == for = ) (请注意:我们将-gt运算符用于>,-lt表示<,==表示=)

To make as few changes as possible double the brackets - to enter 'double bracket' mode (is only valid in bash/zsh not in Bourne shell). 要进行尽可能少的更改,请使用双括号-进入'double bracket'模式(仅在bash / zsh中有效,在Bourne shell中无效)。

If you want to be compatible with sh you can stay in 'single bracket' mode but you need to replace all operators. 如果要与sh兼容,则可以保持'single bracket'模式,但需要替换所有运算符。

In 'single bracket' mode operators like '<','>', '=' are used only to compare strings. 'single bracket'模式下,像'<','>', '=''<','>', '='运算符仅用于比较字符串。 To compare numbers in 'single bracket' mode you need to use '-gt' , '-lt' , '-eq' 要在'single bracket'模式下比较数字,您需要使用'-gt''-lt''-eq'

#!/bin/bash 
read num1
read num2
if [[ $num1 > $num2 ]]
    then 
        echo "X is greater than Y"
elif [[ $num1 < $num2 ]]
    then 
        echo "X is less than Y"
elif [[ $num1 = $num2 ]]
    then 
        echo "X is equal to Y"
fi 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM