如何在 bash 中比较值?

如何在 bash 中比较值?

我正在尝试使用 Ubuntu Mate 16.04 在树莓派上编写一个简单的网页。

这些比较有问题,当 ctemp 为 31 或任何其他温度时,我收到消息“我不知道温度是多少”。

我认为我的比较不正确,但我似乎无法弄清楚如何进行正确的比较。

   #!/bin/bash
echo "<html><body>"
#get temp too and show in images
sensor=`/opt/vc/bin/vcgencmd measure_temp | sed "s/[^0-9]//g"`
#sensor is 10 times higher than actual Core temp.
ctemp=$((sensor/10))
echo "Core Temp: " $ctemp

if [ "$ctemp" >= "20" ] && [ "$ctemp" < "38" ];then   
    echo "<img src=\"cool.png\" alt=\"cool\">"
elif [ "$ctemp" >= "38" ] && [ "$ctemp" < "50" ];then
     echo "<img src=\"mid.png\" alt=\"Normal Operational Temprature\"><br>"

elif [ "$ctemp" >= "50" ];then
     echo "<img src=\"hot.png\" alt=\"Hot\">"
else
     echo "<br>I have no clue what temprature it is<br>"
fi

答案1

man bash

 string1 == string2
   string1 = string2
          True  if  the strings are equal.  = should be used with the test
          command for POSIX conformance.  When used with the  [[  command,
          this  performs  pattern  matching  as  described above (Compound
          Commands).

   string1 != string2
          True if the strings are not equal.

   string1 < string2
          True if string1 sorts before string2 lexicographically.

   string1 > string2
          True if string1 sorts after string2 lexicographically.

   arg1 OP arg2
          OP is one of -eq, -ne, -lt, -le, -gt, or -ge.  These  arithmetic
          binary  operators return true if arg1 is equal to, not equal to,
          less than, less than or equal to, greater than, or greater  than
          or  equal  to arg2, respectively.  Arg1 and arg2 may be positive
          or negative integers.

因此,不要使用>=and <(字符串比较),而要使用-geand -lt(数字比较)。

相关内容