Skip to content

Instantly share code, notes, and snippets.

@knight-of-ni
Created November 12, 2021 13:21
Show Gist options
  • Save knight-of-ni/be323a26209348add30719d9f11e2a58 to your computer and use it in GitHub Desktop.
Save knight-of-ni/be323a26209348add30719d9f11e2a58 to your computer and use it in GitHub Desktop.
Cron safe Mysql dB checker
#!/bin/bash
# Provide MySql user credentials i.e. root
MYSQLUSER="root"
MYSQLPWD="MySecretPassword"
# Make the script cron safe
ID="/usr/bin/id"
MYSQLCHECK="/bin/mysqlcheck"
SYSTEMCTL="/usr/bin/systemctl"
zabbix_stopped=0
##########################
# SUBROUTINE DEFINITIONS #
##########################
cleanUp () {
# Restart the zabbix server if we preveously stopped it
if [ "$zabbix_stopped" -ne "0" ]; then
echo
echo "Starting Zabbix Server..."
echo
$SYSTEMCTL start zabbix-server > /dev/null 2>&1
fi
elapsed=$SECONDS
echo
echo -n "Script elapsed time was "
printf '%dh:%dm:%ds\n' $(($elapsed/3600)) $(($elapsed%3600/60)) $(($elapsed%60))
echo
}
trap cleanUp EXIT
#########################
# INITIAL SANITY CHECKS #
#########################
# We need to be root to run this script
if [ "$($ID -u)" -ne 0 ]; then
echo
echo "ERROR: This script must be run as root. Aborting..."
echo
exit 1
fi
# Check to see if this script has access to all the commands it needs
for CMD in set echo $ID $MYSQLCHECK $SYSTEMCTL; do
type $CMD &> /dev/null
if [ "$?" -ne "0" ]; then
echo
echo "ERROR: The script cannot find the required command \"${CMD}\"."
echo
exit 1
fi
done
#####################
# BEGIN MAIN SCRIPT #
#####################
# Stop the zabbix server service while we check the databases
echo
echo "Stopping Zabbix Server..."
echo
$SYSTEMCTL stop zabbix-server > /dev/null 2>&1
if [ "$?" -eq "0" ]; then
zabbix_stopped=1
else
echo
echo "WARNING: An error was returned when stopping the Zabbix server service..."
echo
fi
# check, repair, and optimize all databases
echo
echo "Begin check and optimization of all sql databases..."
echo
$MYSQLCHECK -u${MYSQLUSER} -p${MYSQLPWD} --auto-repair -o --all-databases
if [ "$?" -eq "0" ]; then
echo
echo "Check and optimization complete..."
echo
else
echo
echo "WARNING: An error was returned while checking all databases..."
echo
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment