前情提要
互联网时代,数据库是一个应用服务的心脏,不管应用体量如何都应做好数据库的备份工作,这篇文章主要实现的是利用 Mysql 自带命令 mysqldump 定时备份数据库的功能。
编写一个备份配置(backup.conf)
[client]
host = 127.0.0.1
port = 3306
user = root
password = 123456
[other]
db_names = db_test,db_test2
backup_dir = /home/mysqlbak/sql/
backup_days = 7
mysqldump_cmd = /usr/bin/mysqldump
编写备份 Shell 脚本(mysqlbak.sh)
#!/bin/bash
CONFIG_FILE_NAME=backup.conf
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
CONFIG_FILE=$SCRIPT_DIR/$CONFIG_FILE_NAME
DB_NAMES=$(grep db_names $CONFIG_FILE | cut -d= -f2)
DB_NAMES_ARR=(${DB_NAMES//,/ })
BACKUP_DIR=$(grep backup_dir $CONFIG_FILE | cut -d= -f2)
BACKUP_DAYS=$(echo $(grep backup_days $CONFIG_FILE | cut -d= -f2))
MYSQLDUMP_CMD=$(grep mysqldump_cmd $CONFIG_FILE | cut -d= -f2)
DATE=`date +%Y%m%d`
TIME=`date +%H%M%S`
echo "[$DATE $TIME]"
echo "Backuping ..."
for DB_NAME in ${DB_NAMES_ARR[@]}
do
TODAY_DIR=$BACKUP_DIR/$DATE
if [ ! -d $TODAY_DIR ]; then
mkdir -p $TODAY_DIR
fi
echo -n " BACKUP $DB_NAME ... "
$MYSQLDUMP_CMD --defaults-extra-file=$CONFIG_FILE --triggers --routines --events $DB_NAME | gzip > $TODAY_DIR/$DB_NAME.$TIME.sql.gz
echo "[OK]"
done
echo "Backup End!"
DELETED_BACKUP_DIRS=$(find $BACKUP_DIR -type d -ctime +$BACKUP_DAYS)
echo "Deleting old data ..."
for DELETED_DIR in $DELETED_BACKUP_DIRS
do
rm -rf $DELETED_DIR > /dev/null 2>&1
echo " $DELETED_DIR ... [DONE]"
done
echo "Delete End!"
设置 Crontab
crontab -e
0 1 * * * /bin/bash /home/mysqlbak/mysqlbak.sh >> /home/mysqlbak/crontab.log
结论
编写一个数据库备份脚本并不是很难,只需要掌握基础的 shell 语法即可,该脚本备份为可配置,比较灵活。备份的 Sql 文件也是经过了 gzip 压缩,解压缩是使用:gzip -d xxxx 即可获取备份的 Sql 文件。
该脚本放在了我的 Github,需要的可以随时 clone 使用,点击访问。
|