Skip to content
Advertisement

Unable to get the absolute value of command output

So I wanted to make a simple script to keep checking the CPU temperature of my RasPi, which is stored in /sys/class/thermal/thermal_zone0/temp , and hence cat /sys/class/thermal/thermal_zone0/temp would give the temp, but like this :

cat /sys/class/thermal/thermal_zone0/temp
38459

which essentially means 38.459 degree Celsius.

I was unable to format the output to get 38.594 °C

My code:

tempT="$(cat /sys/class/thermal/thermal_zone0/temp)"
tempC=$($tempT / 1000)
echo "$tempC °C"

The error I get:

-bash: 38459: command not found
 °C

Thanks

Advertisement

Answer

The simplest would be to use awk.

awk '{print $1/1000}' /sys/class/thermal/thermal_zone0/temp

or with some more control with printf

awk '{printf "%.3fn", $1/1000}' /sys/class/thermal/thermal_zone0/temp

The error you are seeing comes from that you used $( ...), which is a command substitution and tries to run the command inside. So when you do:

$($tempT / 1000)

First $tempT expands to 38459 and then shell tries to run a command named 38459 with two arguments / and 1000. So you see the message 38459: Command not found. Use $((...)) for arithmetic expansion, but shells do not implement floating point arithmetic so you have to use other tools like awk or bc.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement