Execute commands if load average is above in linux


I needed this to do some testing with a load problem I had. One of our server would spike in load for a minute or two, but at random times.
I needed to see what was generating these spikes, but did not want to sit around waiting for it to happen and being ready to hit enter on the commands i needed to run when the load was spiking. So I made this simple little script that you can edit to your needs.

It’s a bash script, and requires the package “bc” to be installed (install it using your package manager if you don’t already have it installed.)

I have tested the script on CentOS and Debian.

I have tried commenting everything in the script as good as possible, but if you have any changes feel free to post a comment.

The script used to monitor load average on a linux server

Copy the script below to a .sh file

#The minimum load average at 1 minute to trigger an event
#run counter, is only used to see that the script is still running.
#enter an infinite loop
while true
echo "Run count: $RUNCOUNT"
#Get the current 1 min average load
LOAD1MIN="$(uptime | awk -F "load average:" '{ print $2 }' | cut -d, -f1 | sed 's/ //g')"
#set true or false, if the load is above the limit specified at the top of the script
RESULT=$(echo "$LOAD1MIN > $LIMIT" | bc)
#If the load is above the trigger limit, then break free of the loop to end the script
if [ "$RESULT" == "1" ]; then
	echo "Load is above $LIMIT!"
	#Add the commands here that you want to execute when the 1min average load is above $LIMIT. One command per line
	#break out of the loop
	#You can remove this break, if you want the script to re-run automatically even when the load has been above $LIMIT.
	#in my case, i needed it to stop once the load was above $LIMIT so i added this break.
	echo "Load not above $LIMIT"
#sleep for 1 second
sleep 1
#clear the screen to make it all pretty
#End of loop, if this it hit, then return to top of loop and start over
#exit the script, since the load was above $LIMIT we don't need to run it anymore
exit 0

Make the script executable

Make it executable with the following command:

chmod +x <name of file>.sh

2 thoughts on “Execute commands if load average is above in linux

  1. Kaushik Hatti

    Thanks for this script. I am a PhD student and had used your script to run my jobs on multi-core unix system. I want to acknowledge your script in my thesis. I want to mention more than just this URL. Can you please provide your name (and anything that you would want me to include, like your host institution/company).


Leave a Reply

Your email address will not be published.