Skip to content


Linux script to automatically shutdown when load average is low

I’ve been using on-demand machines (similar to AWS EC2 and Google Cloud VM instances) to perform large computations. Those machines are both pay-as-you go and pretty expensive, so you want to terminate them as soon as your computations are done.

I’m sure there’s some fancy way, using tools provided by the cloud machine provider, to automatically shut down a machine that’s idle. But I thought, rather than looking for each vendor-specific, complicated (and likely billable) solution, I’d come up with a bash script. And here it goes:

while :
do
  load5M=$(uptime | awk -F'[a-z]:' '{ print $2}' | cut -d, -f1)
  threshold=0.5
  echo $load5M
  if (( $(echo "$load5M < $threshold" | bc -l) )); then
    sudo shutdown now
    break
  fi
  sleep 5
done

It's an infinite loop, with a 5 seconds pause, which gets the load average over the last 5 minutes, displays it, and if it's lower than the defined threshold of 0.5 (that's half a CPU core), immediately stops the machine. Simple enough, apart from the 2 magic lines needed to get the load average and to do a comparison between 2 floats (I found that surprisingly tougher than comparing 2 integers!)

A little warning though: be sure to test it, to check that your provider doesn't automatically restarts a terminated machine. That's quite unlikely, but it would be a shame ^^

Posted in Linux.


0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.



Some HTML is OK

or, reply to this post via trackback.

Please solve the CAPTCHA below in order to fight spamWordPress CAPTCHA