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

执行Shell脚本时出现“-ge: 一元运算符期望”错误求助

问题原因及解决方法

错误根源

  1. if条件语法错误:[$usep -ge ${alert%}] 中,方括号[和表达式、表达式和]之间必须有空格。Shell会把无空格的[$usep识别为一个命令,导致-ge找不到合法操作数,触发“Unary operator expected”错误。
  2. 无效的参数展开:${alert%} 是错误写法,alert变量存储的是数值90,不需要用%进行截断,直接使用$alert即可。
  3. 空变量风险:如果df -h的输出未匹配到/prod,或者awk解析失败,usep变量会为空,此时-ge因缺少操作数也会报错,需要给变量加双引号避免空值问题。

修正后的脚本

to_add=xyz.p@mail.com
alert=90
df -h | grep -e '/prod' | awk '{ print $5"used "$1}' | while read output;
do
    usep=$(echo "$output" | awk '{ print $1}' | tr -d"%")
    echo "$usep"
    # 修正:方括号前后加空格,用$alert替代${alert%},变量加双引号避免空值
    if [ "$usep" -ge "$alert" ]; then
        echo "Alert: Used Percentage is:$usep"
        df -h | mail -s "Alert: out of disk space $usep"  "$to_add"
    fi
done

额外优化建议

  • 可以在使用usep前先判断是否为空,避免后续逻辑出错:
    if [ -z "$usep" ]; then
        echo "Failed to get disk usage percentage"
        continue
    fi
    
  • 用df -P替代df -h可以获得更稳定的可解析输出(-P是POSIX标准格式,避免不同系统的输出差异)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 22:27:34