CentOS Linux下每天自動備份MySQL資料庫

來源:互聯網
上載者:User

CentOS Linux下每天自動備份MySQL資料庫

CentOS Linux下每天自動備份MySQL資料庫

1.先在伺服器下建檔案夾以下3個檔案夾:mkdir /bak,mkdir /bak/bakmysql,mkdir /bak/bakmysqlold 。在/bak/bakmysql檔案夾下建一個shell指令碼:touch /bak/bakmysql/backup.sh 。

給檔案授權:chmod 755 /bak/bakmysql/backup.sh 。

2.編輯shell指令碼:vi /bak/bakmysql/backup.sh
#!/bin/sh
cd /bak/bakmysql
echo "You are in bakmysql directory"
mv bakmysql* /bak/bakmysqlold
echo "Old databases are moved to bakmysqlold folder"
Now=$(date +"%d-%m-%Y")
File=bakmysql-$Now.sql
mysqldump -uroot -p'password' db_bbs > $File
echo "Your database backup successfully completed"
SevenDays=$(date -d -7day  +"%d-%m-%Y")
if [ -f /bak/bakmysqlold/bakmysql-$SevenDays.sql ]
then
rm -rf /bak/bakmysqlold/bakmysql-$SevenDays.sql
echo "You have delete 7days ago bak file "
else
echo "7days ago bak file not exist "
fi

3.shell指令碼:mysqldump -uroot -p'password' db_bbs> $File 這句中的紅色字型請分別換為你自己的mysql資料庫使用者、密碼和database名。指令碼先將/bak/bakmysql檔案夾下bakmysql為檔案名稱開頭的備份檔案移至/bak/bakmysqlold,再產生最新的備份檔案,最後再判斷/bak/bakmysqlold檔案夾中七天前的檔案是否存在,存在則刪除,最後結束。這樣就能自動備份最近七天的資料庫指令碼。

這是博主的伺服器:

4.設定每天自動執行shell指令碼:vi /etc/crontab 在最後加入這樣一行(具體含義請自行參考/etc/crontab中的注釋):0 0 * * * root /bak/bakmysql/backup.sh 。重啟crontab:/sbin/service crond restart 。如果沒有設定crontab為開機自啟動可以如下設定其開機自啟動:chkconfig –level 35 crond on

本文永久更新連結地址:

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.