Do you want to get an alert once your disk is full on Unix, Linux or BSD Systems? In this tutorial we will show you to set up a simple cron script which sends you an email once a specific disk limit is reached.
We use the df command which reports the file system disk space usage including the amount of disk space available.
su) or simply prepend sudo to all commands that require root privileges.Skript preparation
We use the df command with the -P option which make the output POSIX compliant.
df -P /usr
This is a sample output of a RAID 1 disk:
Filesystem 512-blocks Used Avail Capacity Mounted on /dev/mirror/usr 20308312 2966100 15717548 16% /usr
With the grep and awk command we can print out the used disk space for /usr.
df -P /usr | grep /usr | awk '{ print $5}' | sed 's/%//g'
You can also assign the output to a variable:
output=$(df -P /usr | grep /usr | awk '{ print $5}' | sed 's/%//g')
echo $output
Indexed arrays can be used under BASH:
output=($(df -P /usr))
echo "${output[11]}"
Cron skript
This is an example of a BASH cron skript. Change the threshold according to your needs.
#!/bin/bash
FS="/usr"
THRESHOLD=90
OUTPUT=($(LC_ALL=C df -P ${FS}))
CURRENT=$(echo ${OUTPUT[11]} | sed 's/%//')
[ $CURRENT -gt $THRESHOLD ] && echo "$FS file system usage $CURRENT" | mail -s "$FS file system" mail@domain.com
Use the appropriate syntax for CSH or KSH. Now save the script and place the following line into your /etc/crontab to run it as a daily task:
@daily /path/to/script.sh