Hi all,
I am trying to write a script to be able to
- Run top command
- Pick the PIDs that are taking more than 90% of CPU time
- Get more details like what is the script name and location for that PID
- Script should run until I manually kill it by ctrl + C
I have come up with following script for this:
#!/bin/bash
while true; do
filename=`date +"%Y%m%d%H%M%S"`
touch $filename
chmod 755 $filename
top -bn 1 | grep "^ " | awk '{ printf("%-8s %-8s %-8s %-8s\n", $1, $9, $10, $12); }' | head -n 10 >> $filename
while read pid cpu mem command
do
if [ $cpu -ge 90 ]; then
echo "For $pid" >> SlownessStatusReporter_out
cat /proc/$pid/cmdline >> SlownessStatusReporter_out
fi
done < $filename
sleep 5
done
But I think I am not doing data type conversion properly for $cpu at line
if [ $cpu -ge 90 ]; then
I think when I read from $filename cpu is coming as string and inside if condition, I am trying to use it as integer. This guess is from the fact that I keep getting error for the line if [ $cpu -ge 90 ]; then
as below:
./SlownessStatusReporter.sh: line 15: [: %CPU: integer expression expected
./SlownessStatusReporter.sh: line 15: [: 0.0: integer expression expected
./SlownessStatusReporter.sh: line 15: [: 0.0: integer expression expected
./SlownessStatusReporter.sh: line 15: [: 0.0: integer expression expected
./SlownessStatusReporter.sh: line 15: [: 0.0: integer expression expected
./SlownessStatusReporter.sh: line 15: [: 0.0: integer expression expected
./SlownessStatusReporter.sh: line 15: [: 0.0: integer expression expected
./SlownessStatusReporter.sh: line 15: [: 0.0: integer expression expected
./SlownessStatusReporter.sh: line 15: [: 0.0: integer expression expected
./SlownessStatusReporter.sh: line 15: [: 0.0: integer expression expected
When I tried to put $cpu
and 90
in double quotes or tried to use >=
instead of -ge
, I get a different error as below:
./SlownessStatusReporter.sh: line 15: [: %CPU: unary operator expected
./SlownessStatusReporter.sh: line 15: [: 2.0: unary operator expected
./SlownessStatusReporter.sh: line 15: [: 2.0: unary operator expected
./SlownessStatusReporter.sh: line 15: [: 0.0: unary operator expected
./SlownessStatusReporter.sh: line 15: [: 0.0: unary operator expected
./SlownessStatusReporter.sh: line 15: [: 0.0: unary operator expected
./SlownessStatusReporter.sh: line 15: [: 0.0: unary operator expected
./SlownessStatusReporter.sh: line 15: [: 0.0: unary operator expected
./SlownessStatusReporter.sh: line 15: [: 0.0: unary operator expected
./SlownessStatusReporter.sh: line 15: [: 0.0: unary operator expected
Can someone please suggest me how correct this error so my script can work.
I am using:
$ uname -a
Linux hostname 2.6.18-308.13.1.el5 #1 SMP Thu Jul 26 05:45:09 EDT 2012 x86_64 x86_64 x86_64 GNU/Linux
$ echo $SHELL
/bin/bash
$
Thanks in advance.