I have a server that is pretty stable (disk capacity) until a certain event occurs and then the drive grows over the course of two days until it is full. I wrote a very simple bash script but I'm not too happy with parts of it. First, I want to be able to see the capacity as a percent down to the tenths place. Also, doing an evaluation I had to strip my value of any decimal places to compare it against my defined threshold. Lastly I feel that I made too much use of
cut where I could've been more efficient. I'd love to get some tips for improvement.
#! /bin/bash monDrive=/opt prevReading=/root/diskcheckreading.txt percentThreshold=1 emailAlertemail@example.com #Check if log file exists if [ ! -f $prevReading ] then touch $prevReading prev=$(printf "%0.2f\n" $(bc -l <<< $(df /opt | grep opt | cut -d' ' -f24)/$(df /opt | grep opt | cut -d' ' -f23)*100)) echo $prev > $prevReading fi #Get current percentage used of monitored drive current=$(printf "%0.2f\n" $(bc -l <<< $(df /opt | grep opt | cut -d' ' -f24)/$(df /opt | grep opt | cut -d' ' -f23)*100)) #import previous reading prev=$(cat $prevReading) #Calculate the difference results=$(bc -l <<< $current-$prev ) #Convert to percentage results100=$(bc <<< $results*100) #Remove any number after decimal place so that bash can evaluate rescleanup=$(echo $results100 | cut -d'.' -f1) #Convert to percentage percentThreshold100=$(bc -l <<< $percentThreshold*100) #Check if the difference exceeds the threshold if [ $rescleanup -gt $percentThreshold100 ] then printf "\"$monDrive\" has grown $results%% in the past hour.\n\n$(hostname):$(pwd)/$(basename $0)" | mail -s "Disk Alert - $(hostname):$monDrive" $emailAlert fi #log current reading for next check emailecho $current > $prevReading