#!/bin/bash # Script to check free memory, logging it, and if it is below a configured # min value, mailing an alert. Typical usage is to schedule a cron job to # run this regularly. # # Assumes free -m output formatted like: # total used free shared buffers cached # Mem: 538 525 13 0 47 342 # -/+ buffers/cache: 135 403 # Swap: 1023 35 988 # Feel free to edit these configuration values memoryMin=200 emailFrom=memlow emailTo=root logSummary=/var/log/memlow.log logDetails=/var/log/memlow_details.log # Compute some values now=`date +'%Y/%m/%d__%H:%M:%S'` fullReport=`free -m` # Note: Do not try to reuse fullReport here as: # memoryFree=`echo -e $fullReport | grep buffers/cache | awk ... # It loses the newlines and tries to assign "shared" (the fourth # column header) to fullReport. Have to re-execute free -m instead, # which is unfortunate because the numbers can change slightly. memoryFree=`free -m | grep buffers/cache | awk -F' *' '{print $4}'` # Generate the log files echo -e "$now Free memory is $memoryFree MB" >> $logSummary echo -e "\n$now Output of free -m:\n$fullReport" >> $logDetails # Conditionally send e-mail if [ $memoryFree -lt $memoryMin ]; then echo -e "Free memory is low on $HOSTNAME at $now: $memoryFree MB (less than $memoryMin) \n\n\n $fullReport\n\n\nSee $logSummary for historical trend of values.\nSee $logDetails for detailed history." | mail -s "Memory is low ($memoryFree) on $HOSTNAME at $now" -r $emailFrom $emailTo fi