Bash script checking cpu usage of specific process

user2073780 picture user2073780 · Feb 14, 2013 · Viewed 17.9k times · Source

First off, I'm new to this. I have some experience with windows scripting and apple script but not much with bash. What I'm trying to do is grab the PID and %CPU of a specific process. then compare the %CPU against a set number, and if it's higher, kill the process. I feel like I'm close, but now I'm getting the following error:

[[: 0.0: syntax error: invalid arithmetic operator (error token is ".0")

what am I doing wrong? here's my code so far:

#!/bin/bash
declare -i app_pid
declare -i app_cpu
declare -i cpu_limit
app_name="top"
cpu_limit="50"
app_pid=`ps aux | grep $app_name | grep -v grep | awk {'print $2'}`
app_cpu=`ps aux | grep $app_name | grep -v grep | awk {'print $3'}`
if [[ ! $app_cpu -gt $cpu_limit ]]; then
     echo "crap"
else
     echo "we're good"
fi

Obviously I'm going to replace the echos in the if/then statement but it's acting as if the statement is true regardless of what the cpu load actually is (I tested this by changing the -gt to -lt and it still echoed "crap"

Thank you for all the help. Oh, and this is on a OS X 10.7 if that is important.

Answer

Anton Kovalenko picture Anton Kovalenko · Feb 15, 2013

I recommend taking a look at the facilities of ps to avoid multiple horrible things you do.

On my system (ps from procps on linux, GNU awk) I would do this:

ps -C "$app-name" -o pid=,pcpu= | 
    awk --assign maxcpu="$cpu_limit" '$2>maxcpu {print "crappy pid",$1}'