简体   繁体   English

将"top"命令的output重定向到文件时会出现乱码

[英]There will be messy code when redirect output of "top" command to a file

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"并将其out重定向到一个文件中,例如:

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

But there will be messy code in top.log:但是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?如何解决?

When redirecting "top" command output to a file, we need to use the batch mode (-b) according to the manual:将“top”命令output重定向到文件时,我们需要根据手册使用批处理模式(-b):

-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.log 将类似于:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM