Shell脚本 - 获取CPU使用(%CPU)并将其存储到变量中



我正在尝试检索过程的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'定义%CPU和" GREP终端"定义命令(Process)。

如何将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输出返回。

最新更新