【问题标题】:Comparing numbers in bash scripting比较 bash 脚本中的数字
【发布时间】:2017-09-03 07:26:30
【问题描述】:

我编写了这个脚本来比较 bash 中的 2 个数字,但它给了我一些数字的错误答案。 就像我给它输入 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 

【问题讨论】:

  • 要比较数字,请使用-gt 运算符来表示&gt;,使用-lt 表示&lt;-eq 表示=
  • @anubhava 但它对输入“2 和 3”给出了错误的答案
  • Comparing numbers in Bash 的可能重复项。

标签: linux bash shell terminal


【解决方案1】:

这对我有用:

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
}

然后看看结果:

cmp 2 3
X is less than Y

cmp 2 2
X is equal to Y

cmp 2 1
X is greater than Y

由于您使用的是bash,我建议您使用[[ ... ]] 而不是[ ... ] 括号。

【讨论】:

    【解决方案2】:

    您可以尝试使用 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 
    

    【讨论】:

      【解决方案3】:

      为了尽可能减少更改,将括号加倍 - 进入'double bracket' 模式(仅在 bash/zsh 中有效,在 Bourne shell 中无效)。

      如果你想兼容 sh 你可以留在'single bracket'模式但是你需要替换所有的操作符。

      'single bracket' 模式下,'&lt;','&gt;', '=' 等运算符仅用于比较字符串。要在'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 
      

      【讨论】:

      • 我认为您应该在 bash 中使用单个 '['。并且还使用-gt。 ,否则这将在 Bash 中给出错误的输出。
      【解决方案4】:
      #!/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
      

      (请注意:我们将使用 -gt 运算符表示 > , -lt 表示

      【讨论】:

      • 关于最后一行:不,您在 [ ... ] 中使用 -eq 表示数字相等,而不是 ==
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-03
      • 2011-12-19
      • 1970-01-01
      • 2020-01-04
      • 2013-02-21
      • 2016-01-08
      • 2022-10-23
      相关资源
      最近更新 更多