Page 1 of 1

Linux code to display CPU temp and utilisation

Posted: Sun Feb 21, 2021 9:56 am
by chriscambridge
In case anyone is interested, this is the bash script code to display your CPU's temp and % utilisation.

Animated GIF showing script in action:

Image

Link to full screen Youtube video showing script in action:

https://www.youtube.com/watch?v=b0_jVtb ... sCambridge

Full BASH SCRIPT/CODE:

Code: Select all

#!/bin/bash

# Temperature inputs.
TEMP_INPUT=$(echo /sys/class/hwmon/hwmon1/{temp1_input,temp2_input,temp3_input})

PREV_TOTAL=0
PREV_IDLE=0

while true; do
  # Get the total CPU statistics, discarding the 'cpu ' prefix.
  CPU=(`sed -n 's/^cpu\s//p' /proc/stat`)
  IDLE=${CPU[3]} # Just the idle CPU time.

  # Calculate the total CPU time.
  TOTAL=0
  for VALUE in "${CPU[@]}"; do
    let "TOTAL=$TOTAL+$VALUE"
  done

  # Calculate the CPU usage since we last checked.
  let "DIFF_IDLE=$IDLE-$PREV_IDLE"
  let "DIFF_TOTAL=$TOTAL-$PREV_TOTAL"
  let "DIFF_USAGE=(1000*($DIFF_TOTAL-$DIFF_IDLE)/$DIFF_TOTAL+5)/10"

  # Calculate highest CPU Temperature.
  HIGH_TEMP=$(echo "scale=1; $(sort -r $TEMP_INPUT | head -n1) / 1000" | bc)

  # Redirect CPU temperature and % of CPU usage to file.
  echo "$(date '+%H:%M:%S'): +${HIGH_TEMP}°C ${DIFF_USAGE}%"

  # Remember the total and idle CPU times for the next check.
  PREV_TOTAL="$TOTAL"
  PREV_IDLE="$IDLE"

  # Wait before checking again.
  sleep 1
done
INSTRUCTIONS FOR LINUX MINT:

1) Name the code filname.sh

2) Run the following chmod command on the file:

Code: Select all

chmod +x filename.sh
3) Run the file:

Code: Select all

./filename.sh
CHANGE OUTPUT FROM TERMINAL TO TEXT FILE

just change the line:

Code: Select all

# Redirect CPU temperature and % of CPU usage to file.
  echo "$(date '+%H:%M:%S'): +${HIGH_TEMP}°C ${DIFF_USAGE}%"
to:

Code: Select all

# Redirect CPU temperature and % of CPU usage to file.
  echo "$(date '+%H:%M:%S'): +${HIGH_TEMP}°C ${DIFF_USAGE}%" >> cpu.txt

Re: Linux code to display CPU temp and utilisation

Posted: Sun Feb 21, 2021 12:54 pm
by UBT - Timbo
Hi Chris

Thanks for this....just a shame I don't currently run any Linux machines as I'd love to try it out (or give it a "bash" ;-) ).

I'm sure other members might be able to benefit from this :-)

regards
Tim