提供一個 Bash 腳本,可自動遍歷指定資料庫的所有表,執行 CHECK TABLE,若發現錯誤則自動執行 REPAIR TABLE,並可選擇性執行 OPTIMIZE TABLE 優化表結構。
#!/bin/bash
host_name=127.0.0.1
user_name=your_user
user_pwd=your_password
database=your_db
need_optmize_table=false
tables=$(/usr/local/webserver/mysql/bin/mysql -h$host_name -u$user_name -p$user_pwd $database -A -Bse "SHOW TABLES")
for table_name in $tables; do
check_result=$(/usr/local/webserver/mysql/bin/mysql -h$host_name -u$user_name -p$user_pwd $database -A -Bse "CHECK TABLE $table_name" | awk '{ print $4 }')
if [ "$check_result" = "OK" ]; then
echo "It's no need to repair table $table_name"
else
echo $(/usr/local/webserver/mysql/bin/mysql -h$host_name -u$user_name -p$user_pwd $database -A -Bse "REPAIR TABLE $table_name")
fi
# 可選優化
if [ $need_optmize_table = true ]; then
echo $(/usr/local/webserver/mysql/bin/mysql -h$host_name -u$user_name -p$user_pwd $database -A -Bse "OPTIMIZE TABLE $table_name")
fi
done
host_name、user_name、user_pwd、database 為實際值。need_optmize_table 設為 true 可啟用優化。也可直接使用 MySQL 內建工具 mysqlcheck:
mysqlcheck -u root -p --auto-repair --optimize --all-databases
此命令可一次檢查、修復並優化所有資料庫,但耗時較長,視資料量而定。