BASH

Check Server Disk Space and Alert if Low

A bash script to monitor available disk space on a server. It checks all mounted filesystems and alerts if usage exceeds a configurable threshold, preventing outages from full disks.

#!/bin/bash

THRESHOLD=85 # Percentage threshold for disk usage

# Get disk usage for all mounted filesystems, exclude snap, squashfs, tmpfs, devtmpfs
df -h | grep -vE '^Filesystem|tmpfs|cdrom|snap|squashfs|devtmpfs' | awk '{print $5 " " $1}' | while read OUTPUT;
do
  USAGE=$(echo $OUTPUT | awk '{print $1}' | sed 's/%//g')
  FILESYSTEM=$(echo $OUTPUT | awk '{print $2}')

  if (( USAGE > THRESHOLD )); then
    echo "ALERT: Disk usage on $FILESYSTEM is at ${USAGE}%!"
    # Optionally, add email notification here:
    # echo "Disk usage on $FILESYSTEM is at ${USAGE}%!" | mail -s "Disk Space Alert" [email protected]
  fi
done

echo "Disk space check completed."
How it works: This script checks the disk space usage across all mounted filesystems, excluding temporary and virtual filesystems. It uses `df -h` to get human-readable output, then `grep -vE` to filter out irrelevant entries. `awk` and `sed` parse the percentage usage and filesystem name. If any filesystem's usage exceeds the `THRESHOLD` (e.g., 85%), it prints an alert message. This is critical for preventing server outages caused by full disks in web hosting environments.

Need help integrating this into your project?

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

Hire DigitalCodeLabs