Tuesday, November 12, 2013

How to capture top output to a readable format

For this case, we use batch mode in top. From top's manpage:
Starts  top in 'Batch mode', which could be useful for sending output from top to other programs or to a file.  In this mode, top will not accept input and runs until the iterations limit you've set with the '-n' command-line option or until killed.

To use it is very easy, you must provide -b for batch mode, and -n for number of iteration that you desire. You can pipe it to less, tail, head or pipe it to a file, according to your need.

foo@thorium:~$ top -b -n 1 | head

top - 10:47:15 up 3 days, 23:52,  1 user,  load average: 2.01, 0.99, 0.57

Tasks: 140 total,   2 running, 136 sleeping,   0 stopped,   2 zombie

Cpu(s): 13.2%us,  4.9%sy,  0.0%ni, 81.6%id,  0.3%wa,  0.0%hi,  0.0%si,  0.0%st

Mem:   1025608k total,   865376k used,   160232k free,    80332k buffers

Swap:   522236k total,    66468k used,   455768k free,   273996k cached

  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND                                                                                              
1192 root      20   0  122m  65m  10m R 13.8  6.6 559:31.01 Xorg                                                                                                  
19333 foo   20   0  234m  61m  13m S  9.8  6.2 626:59.69 nxplayer.bin                                                                                            
19440 foo   20   0  175m  14m 9612 S  7.9  1.5   0:44.78 lxterminal  

The above command will list 10 lines of top output in batch mode, and being set to iterate only once.

No comments: