BASH

Monitor Disk Space Usage in Bash

Create a simple Bash script to check available disk space on a specific mount point, useful for generating alerts or ensuring critical services have enough storage.

#!/bin/bash

# Configuration variables
MOUNT_POINT="/"      # The disk mount point to check (e.g., /, /var)
THRESHOLD_PERCENT=90 # Percentage threshold for triggering a warning

# Get disk usage for the specified mount point
DISK_USAGE=$(df -h "$MOUNT_POINT" | awk 'NR==2 {print $5}' | sed 's/%//')

# Check if DISK_USAGE is a number
if ! [[ "$DISK_USAGE" =~ ^[0-9]+$ ]]; then
  echo "Error: Could not retrieve disk usage for '$MOUNT_POINT'." >&2
  exit 1
fi

# Compare current usage with the threshold
if (( DISK_USAGE > THRESHOLD_PERCENT )); then
  echo "WARNING: Disk usage is at $DISK_USAGE% on $MOUNT_POINT! This exceeds the ${THRESHOLD_PERCENT}% threshold."
  # Add your alert logic here, e.g., send an email, Slack notification
  # mail -s "Disk Space Alert" [email protected] <<< "Disk usage on $MOUNT_POINT is at $DISK_USAGE%"
else
  echo "Disk usage is normal: $DISK_USAGE% on $MOUNT_POINT."
fi
How it works: This script monitors disk usage and warns you if it exceeds a defined threshold. It uses `df -h` to display disk space information in a human-readable format. `awk 'NR==2 {print $5}'` extracts the percentage usage from the second line (excluding header) and fifth column of `df`'s output. `sed 's/%//'` removes the percentage sign for numerical comparison. The script then checks if the `DISK_USAGE` is greater than `THRESHOLD_PERCENT` and prints a warning, providing a clear point to integrate notification systems like email or instant messaging.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs