1.脚本如下
#usr/bin/sh
#program:用于每周日定时备份全天候mysql文件
#author:sundz
#version:v1 20220521
#定义文件夹和日志文件
date=$(date +%Y%m%d)
log_time=$(date +%H:%M:%S)
backup_floder=/home/aboss/backup/${date}
#mysql_file=mysql_bak_$(date "+%Y_%m_%d")
log_file=/home/aboss/backup/${date}/${date}.log
#检测当天文件夹是否存在
[ ! -d ${backup_floder} ] && mkdir -p ${backup_floder}
#检测当天日志文件是否存在
[ ! -e ${log_file} ] && touch ${log_file}
#检测mysql进程是否存在;全天候A股端口3309
mysql_chk=`ps x | grep 3306 | grep -v 'grep' | wc -l`
if [ "${mysql_chk}" == 1 ]; then
echo "[LOG] ${log_time} check mysql is running" >> ${log_file}
else
echo "[ERROR] ${log_time} check mysql is not running" >> ${log_file}
exit 0
fi
echo "[LOG] ${log_time} check pass" >> ${log_file}
#备份mysql文件,当天文件会被覆盖!!
echo "[LOG] ${log_time} begin backup" >> ${log_file}
cd /home/aboss/mysql/bin
#下一行屏幕不打印的话 加2>>${log_file}
./mysqldump -uroot -p****** -h127.0.0.1 -P3306 --all-databases --flush-privileges --single-transaction --master-data=2 --flush-logs --triggers --routines --events --default-character-set=gbk --hex-blob > all_A_${date}.sql
[ "$?" == 0 ] && echo "[LOG] ${log_time} mysqldmp is done " >> ${log_file} || echo "[ERROR] ${log_time} mysqldmp is wrong " >> ${log_file}
[ "$?" == 0 ] && echo "[LOG] ${log_time} mysqldmp is done " || echo "[ERROR] ${log_time} mysqldmp is wrong "
#压缩拷贝文件
echo "[LOG] ${log_time} begin tar" >> ${log_file}
tar zcvf all_A_${date}.sql.tgz all_A_${date}.sql >> ${log_file} 2>&1
echo "[LOG] ${log_time} over tar" >> ${log_file}
mv all_A_${date}.sql.tgz /home/aboss/backup/${date} 2>>${log_file}
rm all_A_${date}.sql 2>>${log_file}
2.crontab添加定时任务
1.crontab -uaboss -e编辑;相关的配置文件在/var/spool/cron/路径下
每周六9点定时执行,添加如下行:
0 09 * * 6 sh /home/aboss/test.sh
2.service crond restart
3.自动化内容 可以在/var/spool/crond/目录下查看
3.结果
- 生成备份的日志文件和压缩包