shell script to format command output

Hello team,

I am running below command which is giving following output.

bash-3.00$ ps -eo pid,pcpu,args | sort +1n | grep -i java
12 0.0 grep -i java
8804 0.0 /opt/app/ccr/home/ccr/WebSphere/AppServer/java/bin/sparcv9/java -XX:+UnlockDiag
9241 0.0 /opt/app/ccr/home/ccr/WebSphere/AppServer/java/bin/sparcv9/java -XX:+UnlockDiag
18558 0.0 /opt/app/ccr/home/ccr/WebSphere/AppServer/java/bin/java -Xms128m -Xmx512m -DPOL
26719 0.0 /usr/jdk1.6.0_18/bin/java -Djava.compiler=NONE -Djava.security.auth.login.confi
64 0.1 /opt/app/ccr/home/ccr/WebSphere/AppServer/java/bin/sparcv9/java -server -Dwas.s
bash-3.00$

I have requirement to developed script which will check values in column two and if the value exceeds the threshold value , it should send alert with following message echo "$column1 has crossed the threshold value of cpu"

Please help me to prepare script.

 
ps -eo pid,pcpu,args | sort +1n | grep -i java | awk -v threshold=<VALUE> '$2 > threshold {print $1,"has crossed the threshold value of cpu";}'

Hello Anurag,

Thanks for the response. I replaced the value variable with value 6 and i am getting following error.

I need one more update in script if cpu is below threhold value the output should get written in the file.

bash-3.00$ ps -eo pid,pcpu,args | sort +1n | grep -i java | awk -v threshold=6 '$2 > threshold {print $1,"has crossed the threshold value of cpu";}'
awk: syntax error near line 1
awk: bailing out near line 1
bash-3.00$

Use nawk instead of awk.

 
ps -eo pid,pcpu,args | sort +1n | grep -i java | nawk -v threshold=<VALUE> '$2 > threshold {print $1,"has crossed the threshold value of cpu";} $2 <= threshold {print;}'

Thanks Anurag,

This is perfectly working fine. I need one more help,Is it possible to email alert if it cpu has crossed the threshold value.and also when cpu is under threshold it should write the same in file. It would be great if you can explain me the execution of command.

This will put all alerts and command outout in same file

 
ps -eo pid,pcpu,args | sort +1n | grep -i java | nawk -v threshold=<VALUE> '$2 > threshold {print $1,"has crossed the threshold value of cpu";} $2 <= threshold {print;}' > outputFile

If you need it in different files then
All alerts in one file

ps -eo pid,pcpu,args | sort +1n | grep -i java | nawk -v threshold=<VALUE> '$2 > threshold {print $1,"has crossed the threshold value of cpu";}' > alertFile

Rest in another file

ps -eo pid,pcpu,args | sort +1n | grep -i java | nawk -v threshold=<VALUE> '$2 <= threshold {print;}' > outputFile

And content of alertFile can be sent as email using mailx command.
Something like (verify mailx path):

/usr/sbin/mailx -s "Your Subject" ADDRESS_EMAIL < alertFile

Thanks for the response anurag.script is really working fine.

ps -eo pid,pcpu,args |nawk -v threshold=<VALUE> 'tolower($0)~/java/&&$2 <= threshold'