MySQL备份数据库shell脚本
以下为MySQL备份数据库的sh脚本:
#!/bin/bash
# Shell script to backup MySQL database
# 设置数据库连接变量
MyUSER="" # DB_USERNAME
MyPASS="" # DB_PASSWORD
MyHOST="" # DB_HOSTNAME
# 备份数据的目标目录
DEST="" # /home/username/backups/DB
# 邮件通知
EMAIL=""
# 设置多少天之后的旧文件会被删除
DAYS=3
# Linux bin执行文件路径
MYSQL="$(which mysql)"
MYSQLDUMP="$(which mysqldump)"
GZIP="$(which gzip)"
# 获取当前日期dd-mm-yyyy format
NOW="$(date +"%d-%m-%Y_%s")"
# 新建备份子目录
MBD="$DEST/$NOW/mysql"
install -d $MBD
# 忽略备份的数据库列表
SKIP="information_schema
another_one_db"
# 获取所有数据库列表
DBS="$($MYSQL -h $MyHOST -u $MyUSER -p$MyPASS -Bse 'show databases')"
# 归档数据库dump
for db in $DBS
do
skipdb=-1
if [ "$SKIP" != "" ];
then
for i in $SKIP
do
[ "$db" == "$i" ] && skipdb=1 || :
done
fi
if [ "$skipdb" == "-1" ] ; then
FILE="$MBD/$db.sql"
$MYSQLDUMP -h $MyHOST -u $MyUSER -p$MyPASS $db > $FILE
fi
done
# 归档目录,发送邮件通知,清除
cd $DEST
tar -cf $NOW.tar $NOW
$GZIP -9 $NOW.tar
echo "MySQL backup is completed! Backup name is $NOW.tar.gz" | mail -s "MySQL backup" $EMAIL
rm -rf $NOW
# 删除旧文件
find $DEST -mtime +$DAYS -exec rm -f {} \;