0

I try to write simple script to read temperature:

cpu=$(cat /sys/class/thermal/thermal_zone*/temp)
if [$cpu -ge 50000]; then
echo "OK"
else
echo "Not OK"
fi

echo $cpu is fine: 64000 but script output is:

myscript.sh: 2: [64000: not found
Not OK

What is wrong with line 2? Thank You.

Cyrus
  • 84,225
  • 14
  • 89
  • 153
johnyb
  • 1
  • 1
    Please add a suitable shebang (`#!/bin/bash`) and then paste your script at http://www.shellcheck.net/ and try to implement the recommendations made there. – Cyrus May 22 '22 at 08:39
  • 1
    See [Why should there be spaces around `[` and `]` in Bash?](https://stackoverflow.com/q/9581064/2745495) – Gino Mempin May 22 '22 at 08:45

1 Answers1

0

You want to make a few changes here:

  • Add a space between the [ and the $cpu, and before the ] (as per the comments above)
  • Place the $cpu into double quotes, to avoid unexpected results
  • Handle the possibility of maximum values, by picking up the maximum (or minimum, or average).
cpu="$(cat /sys/class/thermal/thermal_zone*/temp | sort -nr | head -1)"
if [ "$cpu" -ge 50000 ] ; then
    echo "OK" 
else
    echo "NOT"
fi

If you prefer the space-less expressions, you can use the arithmetic expressions

cpu="$(cat /sys/class/thermal/thermal_zone*/temp | sort -nr | head -1)"
if ((cpu>50000)) ; then
    echo "OK" 
else
    echo "NOT"
fi
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
dash-o
  • 13,723
  • 1
  • 10
  • 37