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

如何在Bash中实现磁盘空间邮件告警?现有脚本无法运行

Fixing Your Disk Space Alert Bash Script

Let's walk through the issues in your script and fix it step by step so it properly sends alerts when disk usage exceeds your threshold.

Key Issues in the Original Script

  • Your email body is incomplete (Y...), which means the EOF marker won't be recognized properly—this will cause the script to hang or fail entirely.
  • You're only checking the root partition (VAR1) but not the other two partitions you've captured (VAR2 and VAR3), so alerts won't trigger for those.
  • The disk usage extraction commands are redundant: you don't need grep when awk can directly target the data line, making the code cleaner and more efficient.
  • The alert email lacks clear details (like which partition is over the threshold), so the alert won't be actionable.

Fixed & Improved Script

Here's the revised version that addresses all these problems:

#!/bin/bash
THRESHOLD=50
TODAY=$(date)

# Reusable function to check a single partition
check_disk() {
    local partition=$1
    # Extract usage percentage (without the % sign) using POSIX-compliant df output
    local usage=$(df -P "$partition" | awk 'NR==2 {gsub("%","",$5); print $5}')
    
    if [ "$usage" -gt "$THRESHOLD" ]; then
        mail -s "Disk Space Alert: $partition Over Threshold" rupendra@3ess.in << EOF
Date: $TODAY
Critical Alert: Disk usage for partition $partition has exceeded $THRESHOLD%!
Current usage: $usage%
EOF
    fi
}

# Check all your target partitions
check_disk "/"
check_disk "/dev/sda1"
check_disk "/dev/mapper/centos-var"

What Changed & Why

  • Simplified usage extraction: Using df -P ensures consistent, POSIX-compliant output across different Linux distros. awk 'NR==2' skips the header line directly, and gsub removes the percentage sign without needing sed.
  • Function-based structure: The check_disk function eliminates repetitive code—just call it for each partition you want to monitor.
  • Complete, actionable alerts: The email now clearly states which partition is over the threshold, the current usage, and the date, so you know exactly what needs attention.
  • Full coverage: All three partitions you defined are now checked, so you'll get alerts for any of them that cross the threshold.

Quick Testing & Setup Tips

  • Test the script manually first: Temporarily set THRESHOLD to 1 to trigger an alert immediately and verify emails are sent.
  • Make the script executable: Run chmod +x disk_alert.sh before using it.
  • Automate with cron: Add it to your crontab (e.g., 0 * * * * /path/to/disk_alert.sh) to run hourly and get proactive alerts.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:40:48