如何在单行上获取 CPU 百分比和内存使用率?

Ame*_*ola 5 bash

如何在linux上获得一行打印的CPU百分比使用率和RAM百分比?(使用 cli)

我必须将这些输出字符串传递给 LCD 显示器。

多谢

Lev*_*sky 2

您可以解析一些 Unix 实用程序的输出,例如vmstat

$ vmstat
procs -----------memory---------- ---swap-- -----io---- -system-- ----cpu----
 r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa
 1  0  75812 282632 115704 891332    0    1    22    54  138  362 15  2 80  2
$ vmstat | sed -n '3s/ \+/\t/gp' | cut -f5,14
280904  15
Run Code Online (Sandbox Code Playgroud)

上面打印了可用内存和CPU使用率。

如果您想要使用内存,您可以使用另一个实用程序,例如top在批处理模式下,如 CodeGnome 和我在之前的答案中所建议的那样。

$ top -bn1 | sed -rn '3s/[^0-9]* ([0-9\.]+) .*/\1/p;4s/.*,  ([0-9]+) .*/\1/p' | tr '\n' ' '
10.4 3787340
Run Code Online (Sandbox Code Playgroud)

或者要获得百分比,您可以这样做

$ top -bn1 | \
> sed -rn '3s/[^0-9]* ([0-9\.]+) .*/\1/p;4s/[^0-9]*([0-9]+)[^0-9]+([0-9]+) .*/\1 \2/p' | \
> { read cpu; read tot used; echo $cpu $(( 100*used/tot )); }
10.3 94
Run Code Online (Sandbox Code Playgroud)

我确信还有更优雅的解决方案。