21

Is there any way to persist the snapshot of top at that given moment into a file?

I tried

top > top.out

but the contents were nothing like top in STDOUT:

^[[H^[[2J^[(B^[[mtop - 16:09:49 up 18 days, 21:46,  4 users,  load average: 2.00, 1.90, 1.87^[(B^[[m^[[39;49m^[[K
Tasks:^[(B^[[m^[[39;49m^[(B^[[m 286 ^[(B^[[m^[[39;49mtotal,^[(B^[[m^[[39;49m^[(B^[[m   1 ^[(B^[[m^[[39;49mrunning,^[(B^[[m^[[39;49m^[(B^[[m 285 ^[(B^[[m^[[39;49msleeping,^[(B^[[m^[[39;49m^[(B^[[m   0 ^[(B^[[m^[[39;49mstopped,^[(B^[[m^[[39;49m^[(B^[[m   0 ^[(B^[[m^[[39;49mzombie^[(B^[[m^[[39;49m^[[K
Cpu(s):^[(B^[[m^[[39;49m^[(B^[[m  5.9%^[(B^[[m^[[39;49mus,^[(B^[[m^[[39;49m^[(B^[[m  0.1%^[(B^[[m^[[39;49msy,^[(B^[[m^[[39;49m^[(B^[[m  0.0%^[(B^[[m^[[39;49mni,^[(B^[[m^[[39;49m^[(B^[[m 93.5%^[(B^[[m^[[39;49mid,^[(B^[[m^[[39;49m^[(B^[[m  0.3%^[(B^[[m^[[39;49mwa,^[(B^[[m^[[39;49m^[(B^[[m  0.0%^[(B^[[m^[[39;49mhi,^[(B^[[m^[[39;49m^[(B^[[m  0.1%^[(B^[[m^[[39;49msi,^[(B^[[m^[[39;49m^[(B^[[m  0.0%^[(B^[[m^[[39;49mst^[(B^[[m^[[39;49m^[[K
Mem: ^[(B^[[m^[[39;49m^[(B^[[m 64322524k ^[(B^[[m^[[39;49mtotal,^[(B^[[m^[[39;49m^[(B^[[m 46529492k ^[(B^[[m^[[39;49mused,^[(B^[[m^[[39;49m^[(B^[[m 17793032k ^[(B^[[m^[[39;49mfree,^[(B^[[m^[[39;49m^[(B^[[m   141304k ^[(B^[[m^[[39;49mbuffers^[(B^[[m^[[39;49m^[[K
Swap:^[(B^[[m^[[39;49m^[(B^[[m  6289436k ^[(B^[[m^[[39;49mtotal,^[(B^[[m^[[39;49m^[(B^[[m      696k ^[(B^[[m^[[39;49mused,^[(B^[[m^[[39;49m^[(B^[[m  6288740k ^[(B^[[m^[[39;49mfree,^[(B^[[m^[[39;49m^[(B^[[m 15289220k ^[(B^[[m^[[39;49mcached^[(B^[[m^[[39;49m^[[K
^[[6;1H

1 Answer 1

24

The problem is that top by defaults includes ANSI/VT100 escape codes. In this case, it seems like what you want is only the "raw" text output (i.e. not information that some text should be bold etc etc). Luckily, top has built-in support for this mode of operation, called "batch mode" in their documentation.

From the top man page (man top):

-n : Number of iterations limit as:  -n number
     Specifies the maximum number of iterations, or frames, top should
     produce before ending.
-b : Batch mode operation
     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.

So...

top -n 1 -b > top.out

For other command-line utilities that do not have a convenient "-b" type switch like top, it might also be done with ansifilter. Download, compile, and install. Then you could...

top -n 1 | ansifilter > top.out

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .