【问题标题】:compare cpuusage value using shell script使用 shell 脚本比较 cpuusage 值
【发布时间】:2012-03-28 14:41:19
【问题描述】:

如何使用 shell 脚本计算 CPU 使用率值,我得到一个错误,因为 [: =: unary operator 在if [ $message -ne "" ] 行预期

   #!/bin/sh

    expected_cpuusage="95"
    cpu_usage=`top -n 1 -b|grep Cpu|awk '{print $2}'|cut -d"%" -f1""`
    message=""
    if [ $cpu_usage -gt $expected_cpuusage ]    ##{x%?}
    then
       echo "CPU usage exceeded";
       if [ $message -ne "" ]
       then
         message="$message\n\nCPU usage exceeded configured usage limit \nCurrent CPU usage is $cpu_usage\nConfigured CPU usage is $expected_cpuusage";
       else
         message="CPU usage exceeded configured usage limit \nCurrent CPU usage is $cpu_usage\nConfigured CPU usage is $expected_cpuusage";
       fi ;
    fi

【问题讨论】:

  • 解析top 的输出几乎不是正确的方法。尝试man uptime 或直接从/proc 阅读(如果您的架构有)。
  • 我同意@tripleee。这是获得 CPU 利用率的更好方法:bc<<<"scale=3;$(ps ax -o pcpu= | sort -n | xargs printf '+ %s' | cut -c 2- | bc) / $(grep -c ^processor /proc/cpuinfo)"(假设 bash 和 Linux /proc/)。这给出了所有内核的平均值,因此双核系统上一个内核的 50% 利用率将返回 25.000。 “CPU 利用率”部分应该是相当可移植的,只是“多少个内核?”部分不是。
  • 这种方法的一个好处是您可以删除scale=3;,并确保您现在返回一个非浮点数,您可以直接与-gt 一起使用。跨度>

标签: linux shell unix command


【解决方案1】:

Use more quotes:

if [ "$message" -ne "" ]

否则空字符串会弄乱表达式。

更好:

if [ -n "$message" ]

【讨论】:

    【解决方案2】:

    > 是一个重定向操作符。你要-gt

    if [ $cpu_usage -gt $expected_cpuusage ]
    

    这要求 $cpu_usage 看起来像一个整数,如果不是,它将失败并生成错误。 (即,如果它包含 0-9 以外的字符。-gt 不比较浮点值,因此包含 '.' 的字符串将不起作用。)对于浮点比较,使用 expr:

    if expr $cpu_usage \> $expected_cpuusage > /dev/null; then 
    

    使用诸如 [[ 之类的 bash 内置函数可以使用更巧妙的方法进行此比较,但这些结构限制了脚本的可移植性。 您看到的另一个错误发生在您使用空字符串时。尝试使用引号:

    if [ "$message" -ne "" ]
    

    但使用起来更清晰:

    if [ -n "$message" ]
    

    【讨论】:

    • 还是同样的错误,我也为if条件改变了我的问题
    • 更改后我也得到了这个整数表达式
    • 根本问题仍然是缺少引号,如 l0b0 的回答中所述。
    • @triplee,原来的根本问题是他使用 > 而不是 -gt。当问题被编辑为使用 -gt 时,基本问题变成了尝试使用测试来比较浮点值。没有引号是次要的。
    • 这个问题是关于-ne,没有迹象表明它被编辑了。
    猜你喜欢
    • 1970-01-01
    • 2021-10-12
    • 2010-12-08
    • 2013-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-10
    • 2011-02-15
    相关资源
    最近更新 更多