Categories
Scripts

Super simple BASH script to monitor a process

Here’s a little BASH script that I made to monitor a virtual machine on an OS X box. Basically when its CPU usage gets higher than 75%, I get a Growl notification and a spoken warning from Bruce – one of the many Mac voices.

One thing to note:

ps -eo %cpu 207 | tail -1

is where the magic is done. Replace ‘207’ with the PID of whatever you want to monitor. It would be wiser to make this script monitor the process by name, but in my case I have the VM running all the time.

#!/bin/sh

# CPU threshold
readonly THRESHOLD=75
alarmState=0

while true; do
    # make the output of our command a variable
    set `ps -eo %cpu 207 | tail -1`
    # turn float into int by truncating from decimal after
    toInt=${1/.*}
    # if our CPU usage is above our threshold
    if [ "$toInt" -gt "$THRESHOLD" ]; then	
        # if we haven't displayed a Growl notification for this alarm
        if [ "$alarmState" -eq "0" ]; then	
            alarmState=1
            # display a Growl notification
            growlnotify -sm "`date` Warning! CPU is at $toInt!"
        fi
        # shout out our warning
        say -v Bruce "Warning! CPU is at $toInt!"
        # consider putting 'sleep' here
    else
        # CPU usage is below our threshold
        alarmState=0
    fi
    # pause the script for a second
    sleep 1
done