1

How can I get the average CPU temperature from bash on Linux? Preferably in degrees Fahrenheit. The script should be able to handle different numbers of CPUs.

2 Answers 2

2

You do it like so:

Installation

sudo apt install lm-sensors
sudo sensors-detect --auto

get_cpu_temp.sh

#!/bin/bash

# 1. get temperature

## a. split response
## Core 0:       +143.6°F  (high = +186.8°F, crit = +212.0°F)
IFS=')' read -ra core_temp_arr <<< $(sensors -f | grep '^Core\s[[:digit:]]\+:') #echo "${core_temp_arr[0]}"

## b. find cpu usage
total_cpu_temp=0
index=0
for i in "${core_temp_arr[@]}"; do :
    temp=$(echo $i | sed -n 's/°F.*//; s/.*[+-]//; p; q')
    let index++
    total_cpu_temp=$(echo "$total_cpu_temp + $temp" | bc)
done
avg_cpu_temp=$(echo "scale=2; $total_cpu_temp / $index" | bc)

## c. build entry
temp_status="CPU: $avg_cpu_temp F"
echo $temp_status

exit 0

output

CPU: 135.50 F

1
  • 1
    sensors output is not stable, it can change depending on configuration. In scripts, I think I would suggest to use sensors -u output.
    – KamilCuk
    Jan 27, 2020 at 14:36
1

You can also read CPU temperatures directly from sysfs (path may differ from machine/OS to machine/OS though):

Bash:

temp_file=$(mktemp -t "temp-"$(date +'%Y%m%d@%H:%M:%S')"-XXXXXX")
ls $temp_file
while true; do
    cat /sys/class/thermal/thermal_zone*/temp | tr '\n' ' ' >> "$temp_file"
    printf "\n" >> $temp_file
    sleep 2
done

If you're a fish user, you may add a function to your config dir, let's say: ~/.config/fish/functions/temp.fish

Fish

function temp
    set temp_file (mktemp -t "temp-"(date +'%Y%m%d@%H:%M:%S')"-XXXXXX")
    ls $temp_file
    while true
        cat /sys/class/thermal/thermal_zone*/temp | tr '\n' ' ' >> "$temp_file"
        printf "\n" >> $temp_file
        sleep 2
    end
end

Example

enter image description here

3
  • Thank you. I was unaware of those files. What units are those numbers in? Not Celsius.
    – xinthose
    Jan 27, 2020 at 14:30
  • 1
    for e in $(cat /sys/class/thermal/thermal_zone*/temp); do printf "%s " $e just cat /sys/class/thermal/thermal_zone*/temp | tr '\n' ' ' >> "$temp_file". From the man page: tempfile is deprecated; you should use mktemp(1) instead.
    – KamilCuk
    Jan 27, 2020 at 14:32
  • 1
    @xinthose no problem. Those are Celsius times 1000.
    – gmagno
    Jan 28, 2020 at 0:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.