分享一个Mysql数据库备份的shell 脚本。
代码:
#!/bin/bash
# 备份 mysql数据库
# 将mysql备份到目录 /backup 或自定义的目录中
MyUSER="SET-MYSQL-USER-NAME" # USERNAME
MyPASS="SET-PASSWORD" # PASSWORD
MyHOST="localhost" # Hostname
# 获取相关命令的绝对路径
MYSQL="$(which mysql)"
MYSQLDUMP="$(which mysqldump)"
CHOWN="$(which chown)"
CHMOD="$(which chmod)"
GZIP="$(which gzip)"
# 备份文件保存的目录,请根据需要修改
DEST="/backup"
# mysql数据库保存的目录
MBD="$DEST/mysql"
# 主机名
HOST="$(hostname)"
# 获取日期
NOW="$(date +"%d-%m-%Y")"
# File to store current backup file
FILE=""
# Store list of databases
DBS=""
# 备份时要忽略的数据库
IGGY="test"
[ ! -d $MBD ] && mkdir -p $MBD || :
# Only root can access it!
$CHOWN 0.0 -R $DEST
$CHMOD 0600 $DEST
# 获取所有数据库的清单
DBS="$($MYSQL -u $MyUSER -h $MyHOST -p$MyPASS -Bse 'show databases')"
#开始备份
for db in $DBS
do
skipdb=-1
if [ "$IGGY" != "" ];
then
for i in $IGGY
do
[ "$db" == "$i" ] && skipdb=1 || :
done
fi
if [ "$skipdb" == "-1" ] ; then
FILE="$MBD/$db.$HOST.$NOW.gz"
# do all inone job in pipe,
# connect to mysql using mysqldump for select mysql database
# and pipe it out to gz file in backup dir :)
$MYSQLDUMP -u $MyUSER -h $MyHOST -p$MyPASS $db | $GZIP -9 > $FILE
fi
done