How Do I Compare Values in Bash?

How Do I Compare Values in Bash?

Im trying to write a simple webpage on a raspberry pi with Ubuntu Mate 16.04.

There is something wrong with these comparisons, for where ctemp is 31, or any other temperature, I get the message, "I have no idea what the temperature is."

I think my comparisons are off, but I cannot seem to figure out how to get a proper comparison.

   #!/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
7

1 Answer

From 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.

So, rather than comparing with >= and < (string comparison), use -ge and -lt (numeric comparison).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Alexander Ross
Author

Alexander Ross

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.