linux下利用shell腳本和mysqldump熱備份和恢復mysql

對mifeng數據庫進行每週六3:33徹底熱備份,並能夠徹底恢復!html

1、先創建備份腳本

#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目錄。mysql

對於具體備份sql若是不熟悉,能夠看個人這篇文章:mysqldump使用大全sql

2、爲上述腳本制定執行計劃

#crontab -e
30 1 * * * /backup.sh

更多關於crontab知識,參閱:Linux定時任務Crontab命令詳解數據庫

附mysqldump參數說明:MYSQLDUMP參數詳解(轉)寫得很詳細!bash

到了計劃任務執行的時間,執行好後會給咱們發一封郵件,這是給咱們的提示dom

You have new mail in /var/spool/mail/root

根據提示查看這封郵件ui

[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

主要是最後一句,是錯誤緣由,提示文件路徑找不到,由於咱們沒有配置環境變量,因此涉及到路徑的最好寫絕對路徑spa

#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"

3、恢復備份sql文件

cd /mysqlback tar zxvf extmail20170515.tar.gz mv extmail20170515.sql extmail.sql mysql -uroot -p < extmail.sql
相關文章
相關標籤/搜索