Bash by Example: Disk Monitor
Alerting when disk usage exceeds a threshold by monitoring filesystem utilization with df command, parsing percentage values for comparison against limits, implementing notification mechanisms through email or logging, automating monitoring with cron schedules, and preventing system failures from disk space exhaustion.
Code
#!/bin/bash
THRESHOLD=90
# Get disk usage percentage for root partition /
# df -h / -> Human readable
# awk ... -> Extract the percentage column
# sed ... -> Remove the '%' sign
USAGE=$(df / | grep / | awk '{ print $5 }' | sed 's/%//')
echo "Current Disk Usage: $USAGE%"
if [ "$USAGE" -gt "$THRESHOLD" ]; then
echo "CRITICAL: Disk usage is above $THRESHOLD%!"
# In real life: send email or slack notification
# mail -s "Disk Alert" [email protected] <<< "Disk is full!"
else
echo "Disk usage is within normal limits."
fiExplanation
Monitoring system resources is a classic use case for Bash scripting. This script checks the disk usage of the root partition and triggers an alert if it exceeds a defined threshold. It relies on the df (disk free) command, which reports file system disk space usage.
The challenge with df is parsing its output. The output format includes headers and multiple columns. We use a pipeline of text processing tools: grep to select the line for the root partition, awk to extract the 5th column (which typically holds the percentage), and sed (or tr) to strip the "%" symbol so we can perform a numeric comparison.
This pattern—run a command, parse the output, check a condition, and alert—is the foundation of almost all custom monitoring scripts, whether for CPU, memory, or network latency.
Code Breakdown
awk '{ print $5 }' is the standard way to grab the 5th word of a line. Since df output alignment can vary slightly, awk is safer than character counting.$USAGE is a simple integer like "45", allowing valid use of -gt (greater than).
