How can I receive top-like CPU statistics from the shell?

I use this script (from this thread on the Arch boards):

#!/bin/bash
read cpu a b c previdle rest < /proc/stat
prevtotal=$((a+b+c+previdle))
sleep 0.5
read cpu a b c idle rest < /proc/stat
total=$((a+b+c+idle))
CPU=$((100*( (total-prevtotal) - (idle-previdle) ) / (total-prevtotal) ))

Check out sar, as well. Implementations can vary widely from nix to nix, but it should give you basic system stats, at given snapshots. I'm not sure how accurate the values are at the point at which the command is first initialized, but you might play around to see how it compares to top, iostat, etc.

The output is column-based, like top, so you should be able to pipe output to awk or cut to manipulate the results.


Have you looked at collectl? It's handy because you can tailor the output to your needs. See: http://collectl.sourceforge.net/