【问题标题】:Shell scripting not working [closed]Shell脚本不起作用[关闭]
【发布时间】:2018-06-27 19:11:05
【问题描述】:
cpu= $(mpstat | awk '$12 ~ /[0-9.]+/ { printf("%d%%",100 - $12) }' | cut -d. -f1)

如何抑制数字输出?

% 字符串与数字进行比较时失败。

【问题讨论】:

  • #!/bin/sh cpu= $(mpstat | awk '$12 ~ /[0-9.]+/ { printf("%d%%",100 - $12) }' | cut -d.-f1) if [[ "$cpu" -ge 5 ]];然后 message="EC2 用户服务器中的 CPU 利用率已超出。\n当前使用的是 $cpu 。"回声 -e "$message" | mail -s "CPU 利用率监控" "xxx@yyy.com" fi
  • 不要尝试将代码放入 cmets,如果需要澄清,请编辑问题。使用 Control-k 标记问题中的代码。
  • shell 分配中= 后面不能有空格。
  • 另外,idle 始终是最后一列,所以你可以这样做 mpstat|awk 'p{print int(100-$NF)}/%idle/{p=1}'

标签: linux shell awk scripting


【解决方案1】:

不要将% 放在awk 输出中。在创建电子邮件时添加它。您还可以使用 awk 的 int() 函数从输出中删除分数,而不是通过管道传输到 cut

另外,请确保在 cpu 分配中的 = 周围没有任何空格。

cpu=$(mpstat | awk '$12 ~ /[0-9.]+/ {print int(100 - $12) }')
if (( $cpu > 5 ))
then mail -s "CPU Utilization monitoring" "xxx@yyy.com" <<EOF
CPU Utilization is exceeded in Ec2-user Server.
Current use is $cpu%.
EOF
fi

【讨论】:

  • 感谢 Barmar,但我无法接收电子邮件。
  • set -x放在脚本开头可以查看所有命令的踪迹。
  • 听起来awk 没有找到任何符合条件$12 ~ /[0-9.]+/ 的行
  • 如果你这样做mpstat | awk '$12 ~ /[0-9.]+/ }',你会看到什么?
  • 感谢 Barmar,为您提供帮助。我得到了回应。非常感谢。 :)
最近更新 更多