如何修改Bash磁盘检查脚本,遍历完所有磁盘后再退出
磁盘使用率检查脚本优化
原脚本的问题是遇到第一个使用率≥90%的分区就直接退出,导致无法报告其他同样需要告警的分区。下面是修改后的脚本,会遍历所有分区、输出所有符合条件的告警信息后,再判断是否需要退出:
#!/bin/bash LOGFILE="disk_usage.log" exit_code=0 # 遍历所有磁盘分区,提取使用率和分区路径 df -H | awk 'NR>1 {gsub("%", "", $5); print $5, $1}' | while read -r op partition; do if [ "$op" -ge 90 ]; then warning_msg=">> ### WARNING! Running out of space on \"$partition ($op%)\" on $(hostname) as on $(date)" exit_msg=">> There is not enough left storage in the disk to perform the upgrade, exiting..." echo "$warning_msg" >> "$LOGFILE" echo -e "$warning_msg" echo "$exit_msg" >> "$LOGFILE" echo -e "$exit_msg" exit_code=1 # 标记存在严重告警,后续统一退出 elif [ "$op" -ge 85 ]; then warning_msg=">> ### WARNING! Running out of space on \"$partition ($op%)\" on $(hostname) as on $(date)" advice_msg=">> There is enough left storage in the disk to perform the upgrade, but it is recommended to first increase the size of the disk $partition" echo "$warning_msg" >> "$LOGFILE" echo -e "$warning_msg" echo "$advice_msg" >> "$LOGFILE" echo -e "$advice_msg" fi done # 遍历完成后根据状态决定是否退出 if [ "$exit_code" -eq 1 ]; then exit 1 else echo -e ">> There is enough left storage in the disk to continue with the upgrade, OK" fi
关键修改说明:
- 新增
exit_code状态变量,初始为0,检测到≥90%使用率的分区时将其设为1,不立即终止脚本,继续遍历剩余分区 - 优化分区信息提取逻辑:用awk一次性完成去百分号、提取使用率和分区路径操作,减少不必要的管道和子进程调用
- 修复原脚本中的语法错误:将"There enough"修正为"There is enough"
- 把重复的告警文本存入变量,减少代码冗余
- 显式定义日志文件路径,提升脚本可读性
内容的提问来源于stack exchange,提问作者GBT55
相关产品推荐
相关产品推荐

