I am working on a script that:
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.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
For checking if the service is running or not, you could check the exit code. A well written init script should return 0 if the service is good, 1 service is dead but the /var/run pid file exists, and 3 if it is not running at all. Like:
$ service apache2 status; echo $?
* apache2 is running
0
$ service apache2 stop
* Stopping web server apache2
$ service apache2 status; echo $?
* apache2 is not running
3
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.