Magazine Humeur

Bash : how to simply check disk space on linux and take action when a threshold is reached

Publié le 13 novembre 2016 par Christophe_casalegno

Hi all, after showing you how to simply check load average or memory usage on linux, today i'll simply show you how to check disk space and take action if a threshold is reached.

We'll simply use df, grep, awk, cut and if/then to do this :


#!/bin/bash

# Ex alert_threshold=90 -> You will be alerted if your occupied space is more or equal than threshold
alert_threshold=90

# Email for alert
rcpt1="[email protected]"

# Hostname
host=`hostname -f`

i=0
for disk in `df |grep dev |grep -v tmpfs |grep -v udev| awk -F" " '{print $1}' | cut -d/ -f3`
do
space_use=`df | grep $disk | awk -F" " '{print $5}' | cut -d% -f1`

if [ "$space_use" -gt "$alert_threshold" ]
then
i=$((i + 1))
over_threshold["$i"]="$disk"
fi
done

if [ ${#over_threshold[*]} -gt 0 ]
then
echo >/tmp/mail.txt
subject="Disk space over threshold on $host"
echo "">> /tmp/mail.txt
echo "Disks with space problem with more than $alert_threshold% occupied space" >> /tmp/mail.txt
echo "">> /tmp/mail.txt

for disk in ${over_threshold[*]}
do
info_disk=(`df -h | grep $disk | awk -F" " '{print $6, $2, $3, $4, $5}'`)
echo "- Mount point : ${info_disk[O]} - Total space : ${info_disk[1]} - Used space : ${info_disk[2]} - Free space : ${info_disk[3]} - Used space in percents : ${info_disk[4]}" >> /tmp/mail.txt ; echo "" >> /tmp/mail.txt
done

# Now send the email alert

cat /tmp/mail.txt |mail -s "$subject" $rcpt1
fi

Just put it in your crontab and you'll received an alert when you'll use too many space on your disk. You can also replace mail by actions of your choice. You can download the script directly via this weblink : diskcheck.sh or via wget :


wget http://www.christophe-casalegno.com/tools/diskcheck.sh ; chmod +x diskcheck.sh

Enjoy !

-
Christophe Casalegno
https://twitter.com/Brain0verride


Retour à La Une de Logo Paperblog

A propos de l’auteur


Christophe_casalegno 1903 partages Voir son profil
Voir son blog

l'auteur n'a pas encore renseigné son compte l'auteur n'a pas encore renseigné son compte

Magazines