For some reasons it can be very useful to be alerted on some specific file changes (for instance a database error log).
Using inotify-tools I wrote a script that can monitor a file sending alerts to an email address if that file is changed:
#!/bin/sh
#
# Monitor file $1 for changes
# Send an alert emai to $2 if file $1 changes
# usage: file_change_mail_alert.sh /var/log/messages your.name@domain.com
#
if [ -z "$2" ]; then
echo "Usage: file_change_mail_alert.sh
exit 1
fi
#if a inotifywait for this file is already running
if [ $(ps aux | grep inotifywait | grep -c "$1" ) -gt '0' ]; then
echo "A process monitoring the file $1 is already running: $(ps aux | grep inotifywait | grep "$1" )";
exit 1;
fi
#if inotifywait exists
type -P inotifywait &>/dev/null || { echo "Error: This script requires inotifywait(http://wiki.github.com/rvoicilas/inotify-tools/) .... apt-get install inotify-tools ... " >&2; exit 1; }
#if the file exists
if [ -f $1 ]; then
echo "Monitoring file $1 for changes - sending alerts to $2"
while inotifywait -e modify $1; do
sleep 1
changes="$(tail -n5 $1)"
echo "The following change occured in the file $1 : $changes" | mail -s "Change in $1" $2
done
else
echo "Error: File $1 not found"
fi
This script can be started on server startup like this:
/path/to/file_change_mail_alert.sh /var/log/something.log your.email@domain.ro
Or put in in the crontab – once a day (it will exit if it detects that another instance of “itself” is already running)
0 6 * * * /path/to/file_change_mail_alert.sh /var/log/something.log your.email@domain.ro