2

I have been working on a Bash script to beep when the PC is too hot. I have removed the beep to try identifying the problem. What I have so far:

temp=$(sysctl -n hw.acpi.thermal.tz0.temperature | tr -d 'C')
echo $temp

if ["$temp" -gt "30.1"]
then
   echo "temp hot"
else
   echo "temp ok"
fi

My output is

54.1
temp.sh: line 4: [54.1: command not found
temp ok

Removing the if statement just outputs

54.1

so I think it's the if statement that's not working.

Benjamin W.
  • 33,075
  • 16
  • 78
  • 86
  • You should check your code with https://www.shellcheck.net to find syntax errors like this. Once the spacing in `[ ]` is fixed, your question becomes https://stackoverflow.com/questions/8654051/how-to-compare-two-floating-point-numbers-in-bash – Benjamin W. Nov 08 '18 at 16:56
  • See also https://stackoverflow.com/questions/9581064/why-should-there-be-a-space-after-and-before-in-bash – Benjamin W. Nov 08 '18 at 16:57

2 Answers2

1

You should use double parenthesis (( )) to do arithmetic expressions, and since Bash cannot handle decimal values, you just have to remove the dot (as if you want to multiply it by ten).

temp=$(sysctl -n hw.acpi.thermal.tz0.temperature | tr -d 'C')
max_temp=50.2

(( ${temp//./} > ${max_temp//./} )) && echo "temp hot" || echo "temp ok"

Be sure to use the same format for both values (especially leading zeros, 54.10 would become 5410).

If the format cannot be guaranteed, there is a second method, as mentioned by Benjamin W, using bc. You can send to this command a logical operation involving floats, it returns 0 if true, 1 otherwise.

temp=$(sysctl -n hw.acpi.thermal.tz0.temperature | tr -d 'C')
max_temp=50.2

(( $(echo "$temp > $max_temp" | bc) )) && echo "temp hot" || echo "temp ok"
Amessihel
  • 4,794
  • 1
  • 12
  • 36
  • Just dropping the decimal point requires you to know exactly how many digits there are after it. I'd recommend using `bc` instead. – Benjamin W. Nov 08 '18 at 16:54
  • @benjamin-w Yep, as told in my answer it assumes you knew the format (pure bash, bc not required). I edited my answer to provide a `bc` solution. – Amessihel Nov 08 '18 at 17:16
  • Would rounding / truncating be an option. It doesn't need to be that accurate – chris martin Nov 08 '18 at 18:03
0

Your immediate problem is syntax error -- you omitted the space between the command ([ -- /bin/[) and its arguments ($temp). The last argument of [ must be ] -- your script is missing a blank there too, which makes the last argument "30.1"]. The quotes aren't necessary here, BTW, and only make things harder to read.

This is a generic sh-scripting quation, it has nothing to do with FreeBSD nor with temperature-measuring.

Mikhail T.
  • 2,375
  • 1
  • 20
  • 39