How to get the information about cpu idle from top command?

I am using Ubuntu 9.04. I want to write a shell script to get the information about cpu idle from top command at the real time when i call it, compare cpu idle with 20 (20%), if cpu idle > 20 exit 1, vice versa exit 0. Anybody can help me to resolve it ?
Thanks alot.

Have a look here

Please, if you do not mind my asking, WHY are you trying to parse the CPU idle from the top command? There are better/easier ways to get the cpu idle figure. IS there some contraint that you MUST use the figure form top?

#!/bin/bash
a=20
CPUIDLE=$(top -d 0.1 -n 2 | grep '^Cpu(s):'| tail -1 |awk '{print $5}'|sed 's/%.*//')
echo $CPUIDLE
if [ $CPUIDLE -lt $a ]
then
     exit 1
else
     exit 0
fi

When I run, it have error:

root@ubuntu:~# ./phan6.sh
88.5
./phan6.sh: line 5: [: 88.5: integer expression expected

Please help me to fix it.
Thanks in advanced

if [ "$CPUIDLE" -lt "$a" ]

The result still have error:

root@ubuntu:~# ./phan6.sh
88.5
./phan6.sh: line 5: [: 88.5: integer expression expected

Please check it for me.
Thank you very much.

mpstat | tail -1 | cut -d' ' -f35

---------- Post updated 12-03-09 at 04:31 AM ---------- Previous update was 12-02-09 at 03:28 PM ----------

#! /usr/bin/env perl

my $cpu = qx~mpstat | tail -1 | perl -ane 'print $F[10]'~;
exit 1 if ( 100 - $cpu > 20 );

There is the code exiting "1" if you are above 20% CPU idle time accross all processor cores, average.

---------- Post updated at 04:58 AM ---------- Previous update was at 04:31 AM ----------

#! /bin/bash

CPU=$(mpstat | tail -1 | awk '{print $11}' | cut -c1-2);
if [ $CPU -gt 20  ]
then
    exit 1
fi

If you must have bash, instead of Perl.

I found the valid script for me. Thank you very much for your help. :smiley: