Linux code to display CPU temp and utilisation

Having problems installing that new stick of memory? Found some great software or having issues with something? Or maybe want to chat about your PlayStation, X-Box, Nintendo, Sega, even your old Spectrum 48k....! Or maybe something you want to sell or acquire (computing related of course!). Let us know here...
Post Reply
chriscambridge
Active UBT Contributor 1+ yr
Posts: 2178
Joined: Mon Aug 08, 2016 1:56 pm
Location: UK

Linux code to display CPU temp and utilisation

Post 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
UBT - Timbo
UBT Forum Admin
Posts: 9673
Joined: Mon Mar 13, 2006 12:00 am
Location: NW Midlands
Contact:

Re: Linux code to display CPU temp and utilisation

Post 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
Post Reply