MySql指定数据库全量备份,保存七天
1.mysql-bak.sh文件
# 配置变量 DB_USER="root" DB_PASSWORD="xxx" DATABASES=("dbname1" "dbname2") BACKUP_DIR="/data/mysql-bak" DATE=$(date +%Y%m%d) # 创建备份文件名,包括时间戳 for DB_NAME in ${DATABASES[*]} do BACKUP_NAME="${DB_NAME}-${DATE}.sql.gz" # 创建备份 /usr/local/mysql/bin/mysqldump -u ${DB_USER} -p${DB_PASSWORD} --default-character-set=utf8 -q -R -B ${DB_NAME} | gzip > ${BACKUP_DIR}/${BACKUP_NAME} # 删除超过7天的旧备份 rm -f ${BACKUP_DIR}/${DB_NAME}-$(date -d -7day +%Y%m%d).sql.gz done
2.确保脚本可执行,执行以下命令授权
chmod +x /data/mysql-bak/mysql-bak.sh
3.添加定时任务
crontab -e #每天1.30执行备份 30 1 * * * /data/mysql-bak/mysql-bak.sh