MySQL 多数据库的备份

本文介绍了用 –defaults-group-suffix 参数,传递写在指定配置文件中的所有的数据库配置到 mysqldump 命令来同时备份多个库的实现办法。

$ mysqldump  –defaults-group-suffix=_usera –defaults-file=./.my.cnf  usera_a > user_a.sql

./.my.cnf  的格式如下:

[client]
port=3306
password=mypassword
# 脚本中要求 DB 名须和 user 名一致

[client_usera]

# 等号前后有空格隔开

host = hosta
user = usera

[client_userb]
host = hostb
user = userb

具体脚本如下:

DOW=`date +%a`                          # Day of the week e.g. Mon

cat $BACKUPDIR/.my.cnf|while read f1 f2 f3
do
if echo $f1|grep “client_” 1>/dev/null; then
GROUP=`echo $f1|awk -F_ ‘{print $2}’|sed ‘s/]//g’`
fi
[ “$f1” = “user” ]  && DB=”$f3″
[ -z “$DB” -o -z “$GROUP” ] && continue
SQLFILE=”$MYSQLDUMPDIR/$GROUP-$DOW.sql”
mysqldump  –defaults-group-suffix=_$GROUP –defaults-file=$BACKUPDIR/.my.cnf $DB > $SQLFILE
ERROR=$?
GROUP=””; DB=””
[ $ERROR != 0 ] && echo “MySQL backup to $SQLFILE failed with code $ERROR !” && continue
echo “MySQL Backup to $SQLFILE succeeded!”
done