【问题标题】:Shell script - getting cpu usage (%cpu) and storing it into a variableShell 脚本 - 获取 cpu 使用率 (%cpu) 并将其存储到变量中
【发布时间】:2017-11-27 01:19:28
【问题描述】:

我正在尝试检索进程的 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 terminal' 定义命令(进程)。

如何将 cpu 使用率 (%cpu) 的值放入变量中:

declare -x cpuUsage=[%cpu of process]
echo $cpuUsage

【问题讨论】:

  • 我不太确定 0.0 grep terminal 正在输出你想要的东西。有关背景信息,请参阅此 question and its answers

标签: shell terminal


【解决方案1】:

你需要这样的东西来将使用值存储在一个变量中:

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 输出返回的第一个。

【讨论】:

  • 效果很好:) 谢谢。你能告诉我sed 命令的作用吗?
  • sed 命令仅修剪当 cpu 使用率低于 100% 时出现的前导空格,并干扰以下使用空格字符作为分隔符的剪切命令
猜你喜欢
  • 2010-09-08
  • 2014-03-29
  • 1970-01-01
  • 2019-03-18
  • 2017-09-22
  • 1970-01-01
  • 2011-09-11
  • 1970-01-01
  • 2020-04-17
相关资源
最近更新 更多