有没有办法让“top”只运行一次并退出?

Mic*_*lot 17 osx monitoring top

我发现 shell 命令的输出top是粗略了解机器健康状况的一种简单而熟悉的方式。我想top从一台机器上的微型 Web 服务器提供's 的输出(或与它非常相似的东西),用于粗略的监控目的。

有没有办法让 top 只写一次文本输出,而不需要格式化字符?我试过这个:

(sleep 1; echo 'q') | top > output.txt
Run Code Online (Sandbox Code Playgroud)

这似乎与我想要的很接近,除了 (1) 不能保证我不会得到多于或少于一屏的信息,以及 (2) 我必须去除所有终端格式字符。

或者是否有其他top类似命令列出机器范围和进程级内存/CPU 使用率/正常运行时间信息?

(理想情况下,我喜欢一种可移植到 Linux 和 Mac OS X 的策略,因为我们的开发人员使用 Mac,而我们的生产环境是 Linux。)

cuo*_*glm 29

在 Linux 中,你可以试试这个:

top -bn1 > output.txt
Run Code Online (Sandbox Code Playgroud)

来自man top

-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.
....
-n : Number-of-iterations limit as:  -n number
            Specifies  the  maximum  number of iterations, or frames, top
            should produce before ending.
Run Code Online (Sandbox Code Playgroud)

使用 OS X,尝试:

top -l 1
Run Code Online (Sandbox Code Playgroud)

顶部 OSX 联机帮助页

 -l <samples>
              Use logging mode and display <samples> samples, even if 
              standard output is a terminal. 0 is treated  as  infinity.   
              Rather than redisplaying, output is periodically printed in 
              raw form. Note that the first sample displayed will have an 
              invalid %CPU displayed for each process,  as it is calculated 
              using the delta between samples.
Run Code Online (Sandbox Code Playgroud)