Ubuntu – Bash script to sleep at given CPU temperature ~ update for 16.04

16.04cpususpendtemperature

This is a radically updated version of the question.
I have to update this because this question is flagged as duplicate of this one, while this has no valid answer anymore.


  • Initial version of this question, which had the 11.04 tag:

I am new to scripting and linux, my comp gets too hot sometimes and I want to make a script to detect temp1 and if it's over 65 C, it must put it to sleep. I have a diffuculty at comparing values in the script, I couldn't manage to define figures correctly, would anybody fix it please? Here is my stab at it so far

#!/bin/bash

max=65

val=$   sensors | grep '^temp1:' | sed -e 's/.*: \+\([+-][0-9.]\+\)°C.*$/0\1/'

while true; do
    if [[ "$val" > "$max" ]]; then
        sudo /etc/acpi/sleep.sh force
        sleep 1
    else
        sleep 10
    fi
    clear
    sensors
done

The above got an answer with a script that according to the comments was at some point updated to work in 14.04:

 #!/bin/bash

 while true; do
    val=$(sensors | awk '/temp1/ {print $2}')
    max="+75.0"
    if [[ "$val" > "$max" ]]; then
        dbus-send --system --print-reply --dest="org.freedesktop.UPower" /org/freedesktop/UPower org.freedesktop.UPower.Suspend
    fi
    sleep 10
    clear
    sensors
 done
 exit 0

As indicated in the linked question, the above script doesn't work in 16.04.

That question got an answer with a simplistically modified version of the script:

 #!/bin/bash

 while true; do
    val=$(sensors | awk '/temp1/ {print $2}')
    max="+75.0"
    if [[ "$val" > "$max" ]]; then
        systemctl suspend
    fi
    clear
    sensors
 done
 exit 0

But while it does the job (the system goes to sleep when going above 75), it takes more CPU power than expected and pushes the temperature up while running up to 10 degrees celsius; this is more useful, more cooling when not running!

I don't know if the problem is with the initial 11.04 script or with the last change but this needs a fresh answer for 16.04.

Best Answer

I managed to make my own script.

#!/bin/bash
while true; do
   val=$(sensors | awk '/temp1/ {print $2}')
   max="+75.0"
   if [[ "$val" > "$max" ]]; then
       dbus-send --system --print-reply --dest="org.freedesktop.UPower" /org/freedesktop/UPower org.freedesktop.UPower.Suspend
   fi
   sleep 10
   clear
   sensors
done
exit 0

For 16.04 (also here):

#!/bin/bash
while true; do
   val=$(sensors | awk '/temp1/ {print $2}')
   max="+75.0"
   if [[ "$val" > "$max" ]]; then
       systemctl suspend
   fi
   sleep 10
   clear
   sensors
done
exit 0
Related Question