改进 bash 脚本

j0h*_*j0h 4 command-line bash scripts sensors

我有一个四核台式机,我想根据传感器知道平均温度。所以我写了这个 bash 1 衬垫。

echo `sensors -A | awk {'print $3'} | sed 's/+\|(crit\|0:\|°C//g'` |  awk '{print ($1 + $2 + $3 + $4)/4}'
Run Code Online (Sandbox Code Playgroud)

但我确定它并不完美。例如,如果内核数量发生变化,我的脚本就会中断,或者只是不那么准确。我如何编写一个脚本来查看数量或输出值,并针对核心数量进行调整?

如(前面的伪代码):

echo `sensors -A | awk {'print $3'} | sed 's/+\|(crit\|0:\|°C//g'` |  awk '{print ($n + $n+1 <=($number of cores)) )/($number of cores)}'
Run Code Online (Sandbox Code Playgroud)

我希望这是人类可读的。第一部分的输出类似于:

$  echo `sensors -A | awk {'print $3'} | sed 's/+\|(crit\|0:\|°C//g'`
31.0 31.0 26.0 27.0
Run Code Online (Sandbox Code Playgroud)

我可以得到一些关于获得平均 CPU 温度的专业提示吗?

mur*_*uru 6

使用“原始输出”模式sensors更容易编写脚本:

-u    Raw output. This mode is suitable for debugging  and  for  post-
      processing  of  the  output  by  scripts. It is also useful when
      writing a configuration file because  it  shows  the  raw  input
      names which must be referenced in the configuration file.
Run Code Online (Sandbox Code Playgroud)

例如:

$ sensors -Au
coretemp-isa-0000
Physical id 0:
  temp1_input: 63.000
  temp1_max: 85.000
  temp1_crit: 105.000
  temp1_crit_alarm: 0.000
Core 0:
  temp2_input: 51.000
  temp2_max: 85.000
  temp2_crit: 105.000
  temp2_crit_alarm: 0.000
Run Code Online (Sandbox Code Playgroud)

有了这些标记良好的字段,就可以构建一个简单得多的 awk 命令:

sensors -Au | awk '/temp.*_input/{temp += $2; count += 1} END {print temp/count}'
Run Code Online (Sandbox Code Playgroud)

本质上,对于每个temp.*_input字段,添加温度并增加计数,然后在最后打印总数除以计数。