×
×

Script to Monitor Disk Space Usage (Linux)

Back

Below is a script to monitor the disk usage on your VPS or dedicated server running Linux. This script will alert you via email when the disk usage on your machine reaches a configured threshold you set in the script. Simply copy and paste this into a file name of your choice on your server and set it to run on a timed cron job. Preferably, every 15 minutes.

 

#!/bin/bash

#admin email account
ADMIN="enteryouremail@address.here"

# set usage alert threshold
THRESHOLD=85

#hostname
HOSTNAME=$(hostname)

#mail client
MAIL=/bin/mail

# store all disk info here
EMAIL=""

for line in $(df -hP | egrep '^/dev/' | awk '{ print $6 "_:_" $5 }')
do

	part=$(echo "$line" | awk -F"_:_" '{ print $1 }')
	part_usage=$(echo "$line" | awk -F"_:_" '{ print $2 }' | cut -d'%' -f1 )

	if [ $part_usage -ge $THRESHOLD -a -z "$EMAIL" ];
	then
		EMAIL="$(date): Running out of diskspace on $HOSTNAME\n"
		EMAIL="$EMAIL\n$part ($part_usage%) >= (Threshold = $THRESHOLD%)"

	elif [ $part_usage -ge $THRESHOLD ];
	then
		EMAIL="$EMAIL\n$part ($part_usage%) >= (Threshold = $THRESHOLD%)"
	fi
done 

if [ -n "$EMAIL" ];
then
	echo -e "$EMAIL" | $MAIL -s "Alert: Partition(s) almost out of diskspace on $HOSTNAME" "$ADMIN"
fi