centos下mysql自動備份(親測可用)
阿新 • • 發佈:2019-01-04
編寫sh指令碼如下:
#!/bin/bash db_user="root" db_passwd="123456" db_name="test_db" #進入備份目錄將之前的移動到old目錄 cd /mnt/backup/bakmysql echo "you are in bakmysql directory now" mv test_db* /mnt/backup/bakmysqlold echo "Old databases are moved to bakmysqlold folder" #備份目錄 backup_dir="/mnt/backup/bakmysql" #時間格式 time=$(date +"%Y-%m-%d") #mysql 備份的命令,注意有空格和沒有空格 mysqldump -u$db_user -p$db_passwd $db_name > "$backup_dir/$db_name"-"$time.sql" echo "your database backup successfully completed" #這裡將7天之前的備份檔案刪掉 SevenDays=$(date -d -7day +"%Y-%m-%d") if [ -f /mnt/backup/bakmysqlold/pashanhu-$SevenDays.sql ] then rm -rf /mnt/backup/bakmysqlold/pashanhu-$SevenDays.sql echo "you have delete 7days ago bak sql file " else echo "7days ago bak sql file not exist " echo "bash complete" fi
然後通過下面命令將腳步加入系統的計劃任務
crontab -e 0 2 * * * cd /usr/sbin/ && ./bakmysql.sh
儲存退出以後就可以了。
也許需要重啟crontab 啟用命令:/sbin/service crond restart
後期更改~結果如下