Linux下备份MySQL所有数据库的脚本

该脚本的目的是备份MySQL下除系统信息以外的所有的用户创建的数据库。每个数据库单独一个gz文件存放于指定目录里。执行备份操作完毕以后,删除15日以前创建的备份文件。

#!/bin/sh
# mysql_backup_alldb.sh: backup mysql all databases and keep newest 15 days backup.
# -----------------------------
db_user="root"
db_host="localhost"

# the directory for story your backup file.
backup_dir="/opt/backup/mysqldb1/data"

# mysql, mysqldump and some other bin's path
MYSQL="$(which mysql)"
MYSQLDUMP="$(which mysqldump)"
MKDIR="$(which mkdir)"
RM="$(which rm)"
MV="$(which mv)"
GZIP="$(which gzip)"

# check the directory for store backup is writeable
test ! -w $backup_dir && echo "Error: $backup_dir is un-writeable." && exit 0

# the directory for story the newest backup
test ! -d "$backup_dir" && $MKDIR "$backup_dir"

# date format for backup file (dd-mm-yyyy)
time="$(date +"%Y-%m-%d")"

# get all databases
alldbs=`$MYSQL -u $db_user -e "show databases;"| awk '!/Database/&&!/information_schema/'`

for db in $alldbs
do
$MYSQLDUMP -u $db_user -h $db_host $db | $GZIP -9 > "$backup_dir/$time.$db.gz"
done

#delete the oldest backup 15 days ago
find $backup_dir -name "*.gz" -mtime +15 |xargs rm -rf

exit 0;

可以将该脚本设置到crontab定时任务里执行 ,如以下为每天凌晨3点开始执行备份任务。

修改crontab, 增加一行定时任务。

* 3 * * * /opt/backup/mysqldb1/shell/mysql_backup_alldb.sh > /dev/null 2>&1 &
Share Comments
comments powered by Disqus