Here is my code. I kept finding that my service would abend. I have this running every minute now, and it will
- check the service
- start if it’s not running
- send me an email if it’s not running
#!/bin/bash
# Variables
LOG_FILE="/var/log/mariadb_service_monitor.log"
SERVICE_NAME="mariadb" # Change this to "mariadb" if that's your service name
# Log function
log_message() {
local MESSAGE="$1"
echo "$(date +'%Y-%m-%d %H:%M:%S') - $MESSAGE" | tee -a "$LOG_FILE"
}
# Check service status and log output
if systemctl is-active --quiet mariadb; then
echo "$(date +'%Y-%m-%d %H:%M:%S') - Service 'mariadb' is running" >> /var/log/mariadb_service_monitor.log
else
log_message "Service '$SERVICE_NAME' is not running. Attempting to start it."
if systemctl start "$SERVICE_NAME"; then
log_message "Successfully started the '$SERVICE_NAME' service."
else
log_message "Failed to start the '$SERVICE_NAME' service. Please check manually."
fi
fi