🛠️ MySQL Table Repair Automation Script
#!/bin/bash
# === Configuration ===
DB_USER="root"
DB_PASS="your_password"
LOG_FILE="/var/log/mysql_table_repair.log"
TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')
# Optional: List specific databases to check, or leave empty to check all
DATABASES=$(mysql -u$DB_USER -p$DB_PASS -e "SHOW DATABASES;" | grep -Ev "(Database|information_schema|performance_schema|mysql|sys)")
echo "=== MySQL Table Check & Repair Started at $TIMESTAMP ===" >> $LOG_FILE
for DB in $DATABASES; do
echo "Checking database: $DB" >> $LOG_FILE
TABLES=$(mysql -u$DB_USER -p$DB_PASS -D $DB -e "SHOW TABLES;" | tail -n +2)
for TABLE in $TABLES; do
CHECK_RESULT=$(mysql -u$DB_USER -p$DB_PASS -D $DB -e "CHECK TABLE \`$TABLE\`;" | grep -i "error")
if [[ ! -z "$CHECK_RESULT" ]]; then
echo "Found issue in $DB.$TABLE - Attempting repair..." >> $LOG_FILE
REPAIR_RESULT=$(mysql -u$DB_USER -p$DB_PASS -D $DB -e "REPAIR TABLE \`$TABLE\`;")
echo "$REPAIR_RESULT" >> $LOG_FILE
else
echo "$DB.$TABLE is OK." >> $LOG_FILE
fi
done
done
echo "=== MySQL Table Check & Repair Finished ===" >> $LOG_FILE
📌 Instructions
- Save this as
mysql_repair.sh. - Make it executable:
chmod +x mysql_repair.sh
Run it manually or schedule via cron:
crontab -e
Add:
0 3 * * * /path/to/mysql_repair.sh
🔔 Optional: Email Notification (Add at End of Script)
mail -s "MySQL Table Repair Log" [email protected] < $LOG_FILE