Pale Purple

Simple load checking shell script

Below is a simple shell script which can be used to control execution of tasks on a Linux system based on the systems current load value – with the intention that if the 5 minute load average is greater than a given value the script exits with an error return code (1) or completes without error (0).

In this case saved in a file called /usr/local/bin/load_check,

#!/bin/bash

if [ -z $1 ]; then
    echo "Incorrect usage .... " > /dev/stderr
    exit 1 
fi

LOADLIMIT=$1

load_avg=$(uptime | awk -F 'load average:' '{print $2}' | cut -d, -f1)
if [[ $load_avg < $LOADLIMIT ]]; then
    exit 0
fi
exit 1

And usage would look like :

/usr/local/bin/load_check 3 && run/whatever/command

It’s now possible to modify non-essential cron jobs (for example /etc/cron.d/munin) so that they do not run if the system is deemed too busy – so changing :

*/5 * * * *     munin if [ -x /usr/bin/munin-cron ]; then /usr/bin/munin-cron; fi

to

*/5 * * * *     munin if [ -x /usr/bin/munin-cron ]; then /usr/local/bin/load_check 4 && /usr/bin/munin-cron; fi

Will result in munin-cron not running if the load is over 4. Rinse and repeat for other cron jobs which aren’t critical.

Exit mobile version