很多生产上的MySQL数据库都是直接放在Linux服务器上的,用Shell在服务器上做dump备份最简捷直接。如下小脚本,放到定时任务(crontab)中,就可实现每日备份并保留最近7日dump数据的功能。
#! /bin/bash
# Author :
# create_ts :
# program : do a db dump
#
# __init__
ts_delete=$(date --date='7 days ago' +%Y%m%d) # delete time -7 day
ts_create=$(date +%Y%m%d) # dump time +0 today
#
dp_ofpath=/dump/ # dump directory
#
dt_ofpath=${dp_ofpath}${ts_delete} # delete file
ct_ofpath=${dp_ofpath}${ts_create} # create file
#
#
# delete -7
if [ -d ${dt_ofpath} ]; then
rm -rf ${dt_ofpath}
else
> /dev/null
fi
#
#
# dump +0
mkdir -p ${ct_ofpath}
if mysqldump -h -u -p --single-transaction --skip-lock-tables --set-gtid-purged=OFF --routines --triggers --events --databases mydb > ${ct_ofpath}/mydb.sql;
then > /dev/null
else
echo -e "\n $(date) ← dump failed \n" 1>> ${dp_ofpath}err.log
fi