Shell – Log monitoring using shell script

monitoringshell-script

I would like to monitor a log file for errors and then send an email to administrators.

The log file contains data like below

11 Aug 02:30 Service1 restarted
11 Aug 05:35 Service1 restarted
11 Aug 08:43 Service2 restarted
11 Aug 11:20 Service1 restarted
11 Aug 14:53 Service2 restarted

I would like to create a script which runs for every 5 minutes and checks the last occurrence of service restart and send an email.

For example : if the script runs at 02:35 it sees that Service1 restarted so it will send an email like Service1 restarted at 02:30 . Now when the script runs at 5:45 then it should send email that Service1 restarted at 05:35 only (should not include 02:35 restart)

Is there a way to achieve this requirement ? I am basically new to Linux and Shell scripting

Best Answer

Start by making a five minute crontab:

*/5 * * * * myscript.sh

Which runs myscript.sh (in $HOME dir)

 #!/bin/bash
 tail -1 /path/to/file.log > /some/dir/after
 if cmp -s /some/dir/after /some/dire/before
 then
     cat /some/dir/after | mail -s "restart" admin@exemple.com
     cp /some/dir/after /some/dir/before
 fi

With the correct values (of course).

Note that this implies there will not be two restarts within five minutes.

Related Question