BASH
Monitor Disk Usage and Send Email Alerts in Bash
Implement a Bash script to monitor disk space usage on your server and send an email alert when a specified threshold is exceeded, preventing critical storage issues.
#!/bin/bash
# --- Configuration ---
THRESHOLD=85 # Percentage threshold for disk usage (e.g., 85 for 85%)
EMAIL_RECIPIENT="[email protected]" # Email address for alerts
HOSTNAME=$(hostname)
LOG_FILE="/var/log/disk_monitor.log"
# Note: 'mail' command (from mailutils/postfix) must be installed and configured
# for sending emails. On most systems, you can install it via:
# sudo apt-get install mailutils (Debian/Ubuntu)
# sudo yum install mailx (RHEL/CentOS)
# --- Create log directory if it doesn't exist ---
mkdir -p "$(dirname "$LOG_FILE")" || { echo "Failed to create log directory. Exiting." >&2; exit 1; }
# --- Function to send email alert ---
send_alert() {
local SUBJECT="Disk Usage Alert on $HOSTNAME"
local MESSAGE="The following disk partitions exceed the ${THRESHOLD}% usage threshold:
"
MESSAGE+="$1" # Pass the df output for partitions exceeding threshold
MESSAGE+="
Full disk usage details:
$(df -h)"
echo -e "$MESSAGE" | mail -s "$SUBJECT" "$EMAIL_RECIPIENT"
if [ $? -eq 0 ]; then
echo "$(date): Email alert sent to $EMAIL_RECIPIENT for high disk usage." | tee -a "$LOG_FILE"
else
echo "$(date): Failed to send email alert to $EMAIL_RECIPIENT." | tee -a "$LOG_FILE"
fi
}
echo "$(date): Starting disk usage check." | tee -a "$LOG_FILE"
# --- Get disk usage for all mounted filesystems, excluding specific types ---
# -x tmpfs: Exclude temporary file systems
# -x devtmpfs: Exclude device temporary file systems
# -x squashfs: Exclude squashfs (read-only compressed file systems)
# -x cgroup: Exclude cgroup
# -x autofs: Exclude autofs
# -x overlay: Exclude overlay filesystems (common in Docker)
DF_OUTPUT=$(df -h --total -x tmpfs -x devtmpfs -x squashfs -x cgroup -x autofs -x overlay 2>/dev/null)
# --- Initialize an empty string for partitions exceeding threshold ---
ALERT_PARTITIONS=""
# --- Process each line of df output, skipping header and total ---
echo "$DF_OUTPUT" | tail -n +2 | grep -v 'total' | while read -r line; do
USE_PERCENT=$(echo "$line" | awk '{print $5}' | sed 's/%//g') # Extract percentage, remove '%'
FILESYSTEM=$(echo "$line" | awk '{print $1}')
MOUNTPOINT=$(echo "$line" | awk '{print $6}')
# --- Check if percentage exceeds threshold and is a valid number ---
if [[ "$USE_PERCENT" =~ ^[0-9]+$ ]] && [ "$USE_PERCENT" -ge "$THRESHOLD" ]; then
ALERT_PARTITIONS+="$line
"
echo "$(date): WARNING: Filesystem '$FILESYSTEM' mounted at '$MOUNTPOINT' is at ${USE_PERCENT}% usage." | tee -a "$LOG_FILE"
fi
done
# --- Send alert if any partitions exceeded the threshold ---
if [ -n "$ALERT_PARTITIONS" ]; then
send_alert "$ALERT_PARTITIONS"
else
echo "$(date): All monitored disk partitions are within the ${THRESHOLD}% usage limit." | tee -a "$LOG_FILE"
fi
echo "$(date): Disk usage check finished." | tee -a "$LOG_FILE"
How it works: This script monitors the disk usage of your server's partitions and sends an email alert if any partition exceeds a predefined threshold. It uses `df -h` to get human-readable disk usage, filters out irrelevant filesystems (like `tmpfs`), and then iterates through the output to check the usage percentage. If a threshold is met, it composes and sends an email via the `mail` command, providing details of the offending partitions and overall disk status, while also logging actions.