linux下利用shell脚本和mysqldump热备份和恢复mysql
对mifeng数据库进行每周六3:33完全热备份,并可以完全恢复!
一、先建立备份脚本
#vi /mifengbackup/backup.sh #!bin/bash cd /mifengbackup echo "You are in backup dir" mv backup* /oldbackup echo "Old dbs are moved to oldbackup folder" File = backup-$Now.sql mysqldump -uroot -p123456 --quick --databases database-names --flush-logs --single-transaction > $File echo "Your database backup successfully completed"
上面脚本文件保存为backup.sh,并且系统中已经创建两个目录/oldbackup和/mifengbackup。每次执行backup.sh时都会先将/mifengbackup目录下所有名称为backup开头的文件移到/oldbackup目录。
对于具体备份sql如果不熟悉,可以看我的这篇文章:mysqldump使用大全
二、为上述脚本制定执行计划
#crontab -e 30 1 * * * /backup.sh
更多关于crontab知识,参阅:Linux定时任务Crontab命令详解
附mysqldump参数说明:MYSQLDUMP参数详解(转)写得很详细!
到了计划任务执行的时间,执行好后会给我们发一封邮件,这是给我们的提示
You have new mail in /var/spool/mail/root
根据提示查看这封邮件
[root@localhost mail]# vi root X-Original-To: root Delivered-To: root@localhost.localdomain Received: by localhost.localdomain (Postfix, from userid 0) id 46BD24493CA2; Sat, 22 Dec 2018 03:33:02 -0800 (PST) From: "(Cron Daemon)" <root@localhost.localdomain> To: root@localhost.localdomain Subject: Cron <root@localhost> /backup.sh Content-Type: text/plain; charset=UTF-8 Auto-Submitted: auto-generated Precedence: bulk X-Cron-Env: <XDG_SESSION_ID=63> X-Cron-Env: <XDG_RUNTIME_DIR=/run/user/0> X-Cron-Env: <LANG=en_US.UTF-8> X-Cron-Env: <SHELL=/bin/sh> X-Cron-Env: <HOME=/root> X-Cron-Env: <PATH=/usr/bin:/bin> X-Cron-Env: <LOGNAME=root> X-Cron-Env: <USER=root> Message-Id: <20181222113302.46BD24493CA2@localhost.localdomain> Date: Sat, 22 Dec 2018 03:33:02 -0800 (PST) /bin/sh: /backup.sh: No such file or directory
主要是最后一句,是错误原因,提示文件路径找不到,因为我们没有配置环境变量,所以涉及到路径的最好写绝对路径。
#vi /usr/local/mifengbackup/backup.sh #!bin/bash cd /usr/local/mifengbackup echo "You are in mifengbackup dir" mv backup* /usr/local/oldbackup echo "Old dbs are moved to oldbackup folder" File = backup-$Now.sql mysqldump -h177.77.177.177 -uroot -p123456 --quick --databases mifeng --flush-logs --single-transaction > $File echo "Your database backup successfully completed"
三、恢复备份sql文件