备份脚本如下:
#!/bin/bash
BACKUP_PATH=/opt/backup/<backup_dir>
MYSQL_DUMP=/usr/bin/mysqldump
BACKUP_TIME=$(date +%Y%m%d.%H%M)
BACKUP_DB=<db_name>
DB_USER=<username>
DB_PAWD=<password>
${MYSQL_DUMP} -u${DB_USER} -p${DB_PAWD} ${BACKUP_DB} > ${BACKUP_PATH}/${BACKUP_DB}.sql
if [ $? -ne 0 ];then
echo "${BACKUP_TIME} mysqldump error " >> ${BACKUP_PATH}/dump.log
exit 1
fi
tar -zcvf ${BACKUP_PATH}/${BACKUP_DB}.${BACKUP_TIME}.tar.gz ${BACKUP_PATH}/${BACKUP_DB}.sql
rm -f ${BACKUP_PATH}/${BACKUP_DB}.sql
#删除10天前的文件
find ${BACKUP_PATH} -name "*.tar.gz" -mtime +10 -exec rm -rfv {} \;
exit 0
<backup_dir>:备份目录
<db_name>:数据库名称
<username>:数据库用户名
<password>:数据库密码
写好脚本之后,需要将脚本添加到Linux的定时任务中
crontab -e # 编辑执行计划脚本
添加下面的内容
# 每小时执行一次备份脚本
0 */1 * * * bak_mysqldump.sh