#!/bin/bash
echo '###### 每天 自动备份数据库 ######'
# 设置环境变量
DATE=$(date "+%Y%m%d%M")
USERNAME=root
PASSWORD=12345678
DB=confluence
DIR=/home/mysql/mysql3306/data/dbbackup/mysql
RW=`crontab -u root -l |awk -F "/" 'NR==1{print $NF}'`
systemctl enable crond >/dev/null
systemctl start crond >/dev/null
JHYX=`systemctl status crond|grep running|awk -F " " 'NR==1{print $3}'`
if [ "$JHYX" != "(running)" ];then
echo 任务计划服务未能称正常启动,程序退出!
exit 10
fi
echo '获取系统日期:' $DATE
if [ "$RW" == "mysql_backup.sh" ];then
echo "crontab exist"
else
echo "*/1 * * * * source /home/mysql/mysql3306/data/dbbackup/mysql_backup.sh" >>/var/spool/cron/root
fi
if [ ! -d "$DIR" ]; then
mkdir -p $DIR
fi
cd $DIR
echo '开始备份...' $(date "+%Y-%m-%d %H:%M:%S")
/usr/bin/mysqldump -u$USERNAME -p$PASSWORD $DB | gzip > mysql_$DATE.sql.gz
echo '备份完成' $(date "+%Y-%m-%d %H:%M:%S")
find $DIR -mtime +7 -name "*.sql.gz" -exec rm -rf {} \;