You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用top与Awk监控CPU空闲率遇100值报错的解决咨询

解决CPU空闲率为100%时监控脚本的报错问题

问题现象

当CPU空闲率达到100%时,监控脚本抛出如下错误:

no 0 97.7
awk: BEGIN{print(n1<n2)?"1":"0"}: No such file or directory
yes 100

原脚本内容:

minidle=5
while true;
do
    cpu_idle=`top -b -n1 | grep -o "[0-9]*.[0-9]\+% idle"|awk -F% '{print $1}'`
    r=`awk -v n1=$cpu_idle -v n2=$minidle 'BEGIN{print(n1<n2)?"1":"0"}'`
    if [ $cpu_usage == 100 ]; then
        echo "yes" $r $cpu_idle
    else
        echo "no" $r $cpu_idle
    fi
    sleep 1
done

直接手动设置cpu_idle=100时无报错,需排查问题根源并修复。

错误原因

  1. 正则匹配失效:原正则[0-9]*.[0-9]\+% idle仅能匹配带小数的空闲率(如97.7%),当空闲率为100%时,格式为100% idle(无小数部分),grep无法匹配,导致cpu_idle变量为空。
  2. 空变量引发awk参数异常:当cpu_idle为空时,awk命令会被解析为awk -v n1= -v n2=5 'BEGIN{print(n1<n2)?"1":"0"}',shell会错误地将BEGIN{...}当作要读取的文件,从而抛出“No such file or directory”。
  3. 变量名错误:判断条件中使用了未定义的$cpu_usage变量,实际应该用$cpu_idle。

修复方案

修改后的脚本

minidle=5
while true;
do
    # 修正正则,支持匹配整数/小数格式的空闲率,转义点号避免匹配任意字符
    cpu_idle=$(top -b -n1 | grep -o "[0-9]*\.?[0-9]+% idle" | awk -F% '{print $1}')
    # 给变量加双引号,避免空值导致awk参数解析错误
    r=$(awk -v n1="$cpu_idle" -v n2="$minidle" 'BEGIN{print(n1<n2)?"1":"0"}')
    # 修正变量名,给变量加双引号防止空值引发语法错误
    if [ "$cpu_idle" = 100 ]; then
        echo "yes" "$r" "$cpu_idle"
    else
        echo "no" "$r" "$cpu_idle"
    fi
    sleep 1
done

关键修复点

  • 调整正则表达式为[0-9]*\.?[0-9]+% idle,同时转义点号(\.),确保能匹配100% idle和97.7% idle两种格式。
  • 变量赋值使用$()替代反引号,提升可读性;所有变量引用添加双引号,避免空值或特殊字符导致的语法问题。
  • 将判断条件中的$cpu_usage改为$cpu_idle,修正变量名错误。

内容的提问来源于stack exchange,提问作者fuxq

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 10:30:21