Home > Software engineering >  There will be messy code when redirect output of "top" command to a file
There will be messy code when redirect output of "top" command to a file

Time:01-23

Not sure whether there are existing similar questions already. Sometimes we need to execute "top" for once and redirect its out to a file, such as:

top -n 1 -o %CPU > top.log

But there will be messy code in top.log:

^[[?1h^[=^[[?25l^[[H^[[2J^[(B^[[mtop - 16:27:45 up 916 days, 17:43, 152 users, load average: 5.51, 5.39, 5.42^[(B^[[m^[[39;49m^[(B^[[m^[[39;49m^[[K

How to fix it?

CodePudding user response:

When redirecting "top" command output to a file, we need to use the batch mode (-b) according to the manual:

-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 we can fix the issue by:

top -b -n 1 -o %CPU > top.log

And top.log will be something like:

top - 16:35:07 up 916 days, 17:50, 152 users, load average: 4.68, 4.96, 5.24

Tasks: 2106 total, 4 running, 2065 sleeping, 8 stopped, 22 zombie

%Cpu(s): 9.7 us, 5.8 sy, 0.0 ni, 84.5 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st

  • Related