Script that will email the last few lines of error logs ..
I am working on a script that:
- checks if mysql and apache are running
- if not, it sends an email and then attempts to restart the non-running service
I would like to add the last few lines of the error logs to the email. Here is what I have so far. The check works, the restart works, sending email works, but am not getting my error messages from the log:
#!/bin/bash
#ver. 1
##this script will check mysql and apache
##if that service is not running
##it will start the service and send
##an email to you
##set your email address
EMAIL="email@yourdomain.com"
##list your services you want to check
SERVICES=( 'mysql' 'apache2' )
#### DO NOT CHANGE anything BELOW ####
for i in "${SERVICES[@]}"
do
###IF APACHE IS NOT RUNNING####
if [[ "$(service $i status)" =~ "not" ]]
then
service $i start
MESSAGE= "$(tail -5 /var/log/$i/error.log)"
SUBJECT="$i down on $(hostname) $(date) "
echo "$MESSAGE mysql" | mail -s "$SUBJECT" "$EMAIL"
fi
###IF MYSQL IS NOT RUNNING####
if [[ "$(service $i status)" =~ "stop" ]]
then
service $i start
MESSAGE= "$(tail -5 /var/log/$i/error.log)"
SUBJECT="$i down on $(hostname) $(date) "
echo "$MESSAGE " | mail -s "$SUBJECT" "$EMAIL"
fi
done
Any tips on getting info from the error logs into the email?
Also, my loop would be much better if all services had the same status message...I wonder if there is a better way of checking if the service is running that will return the same result for all services.
Is the space after
MESSAGE=
just something in your question, or is that in the actual code? If I remove the space, it works for me: