如何在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 theEOFmarker 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 (VAR2andVAR3), so alerts won't trigger for those. - The disk usage extraction commands are redundant: you don't need
grepwhenawkcan 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 -Pensures consistent, POSIX-compliant output across different Linux distros.awk 'NR==2'skips the header line directly, andgsubremoves the percentage sign without needingsed. - Function-based structure: The
check_diskfunction 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
THRESHOLDto 1 to trigger an alert immediately and verify emails are sent. - Make the script executable: Run
chmod +x disk_alert.shbefore 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
相关产品推荐
相关产品推荐

