我在macOS上。我想编写一个bash脚本,它暂停0.5秒钟(即睡觉),而某个进程(我只知道命令名)使用的CPU超过了5%。我可以
pgrep command_name
然后
ps -p PID -o %cpu | tail -1 | cut -c 3-5
若要获得CPU使用率,并在while循环中使用此数字,请执行以下操作。这是否可以做得更优雅(最好是在一行代码中)?
发布于 2021-07-05 19:24:09
您可以通过使用命令替换来简化它:
ps -p $(pgrep firefox) -o %cpu | tail -1 | cut -c 3-5恐怕我没有可测试的mac,因此以下内容可能无法在您的系统上运行,但是在Linux上,我们可以使用%cpu=来避免打印标题:
$ ps -p $(pgrep firefox) -o %cpu
%CPU
23.3
$ ps -p $(pgrep firefox) -o %cpu=
23.3这意味着ps -p $(pgrep firefox) -o %cpu=就足以只给出数字。
https://unix.stackexchange.com/questions/657084
复制相似问题