1. 给名为test的数据库,写备份脚本 mysql_auto_backup.sh:
#!/bin/sh
DATABASE_Name=test
# current running shell path
BASEPATH=$(cd `dirname $0`; pwd)
DATABASE_BACKUP_PATH=$BASEPATH/ppwkBackup
echo "Begin backup $DATABASE_Name database..."
if [ ! -d $DATABASE_BACKUP_PATH ];then
mkdir -p $DATABASE_BACKUP_PATH
fi
# begin to backup database
/usr/local/mysql/bin/mysqldump -Y -F -E -x -l -u root -padx^1pk_u7Yv --default-character-set=utf8mb4 --add-drop-database --add-drop-table --add-locks --add-drop-trigger -B $DATABASE_Name > $DATABASE_BACKUP_PATH/mysqlbackup-`date +%Y-%m-%d-%H%M%S`.sql
if [ 0 -eq $? ];then
echo $(date +"%Y-%m-%d %H:%M:%S") "$DATABASE_Name Database backup success!" >> /root/DBBackLog.log sync
else
echo $(date +"%Y-%m-%d %H:%M:%S") "$DATABASE_Name Database backup error!" >> /root/DBBackLog.log
exit
fi
# Delete beyond 15 days backup sql files
find $DATABASE_BACKUP_PATH/ -mtime +15 -name "*.sql" -exec rm -rf {} \;
echo "Backup $DATABASE_Name database finished!"
# recovery $DATABASE_Name database
# mysql -hlocalhost -uroot -p123456 --database $DATABASE_Name< mysqlbackup-2018-05-23-13:44:42.sql
更改备份脚本 mysql_auto_backup.sh为可执行权限:
chmod +x mysql_auto_backup.sh
注意:crontab执行的脚本的mysqldump命令要用绝对路径,不能用相对路径,不然不能备份数据
2. 添加备份脚本到crontab的定时任务中:
查看crontab系统任务调度的配置文件:
cat /etc/crontab
crontab -e
0 4 * * * /data/mysql/mysql_auto_backup.sh > /dev/null 2>&1
每天4点执行一次备份。
查看是否添加到crontab定时任务中:
crontab -l
或者查看日志看某个job有没有执行/报错 :
tailf /var/log/cron
crond 状态、重新加载和重启:
service crond status 或者 systemctl status crond
service crond reload 或者 systemctl reload crond
service crond restart 或者 systemctl restart crond