Shell脚本-获取cpu使用率(%cpu)并将其存储到变量中
我试图检索进程的cpu使用率(%cpu),并将其存储到变量中。 我能够使用Shell脚本显示%cpu和命令:Shell脚本-获取cpu使用率(%cpu)并将其存储到变量中,shell,terminal,Shell,Terminal,我试图检索进程的cpu使用率(%cpu),并将其存储到变量中。 我能够使用Shell脚本显示%cpu和命令: echo Enter the process name you wish to fetch: read pn #Displays %cpu of process ps -eo %cpu,command | grep $pn 输出: Enter the process name you wish to fetch: terminal 0.0 grep terminal “0.0”定义%
echo Enter the process name you wish to fetch:
read pn
#Displays %cpu of process
ps -eo %cpu,command | grep $pn
输出:
Enter the process name you wish to fetch:
terminal
0.0 grep terminal
“0.0”定义%cpu,“grep terminal”定义命令(进程)
如何将cpu使用率(%cpu)的值放入如下变量中:
declare -x cpuUsage=[%cpu of process]
echo $cpuUsage
您需要这样的东西来将使用值存储在变量中:
echo Enter the process name you wish to fetch:
read pn
cpuusage=`ps -eo %cpu,command | grep $pn | grep -v grep | head -n 1 | sed 's,^ *,,' | cut -d ' ' -f 1`
echo $cpuusage
请注意,如果许多进程与给定名称匹配,它只会获取ps输出返回的第一个进程。我不太确定
0.0 grep terminal
是否正在输出您想要的内容。请看下面的一些背景。它工作得很好:)谢谢。请告诉我sed
命令的作用是什么?sed命令只修剪cpu使用率低于100%时出现的前导空格,并干扰以下使用空格作为分隔符的cut命令