1. 程式人生 > 其它 >mysql自動備份指令碼

mysql自動備份指令碼

MySQL使用mysqldump備份資料庫指令碼手工執行成功 crontab定時卻失敗的解決方法

用crontab自動備份MySQL的時候匯出總是為空,原因是corn的環境變數中沒有mysqldump,所以用crontab執行mysqldump的時候要加上絕對路徑,如:/yourMySQLPath/bin/mysqldump xxxxxxx這樣就可以了!
如果不知道絕對路徑可以用ps -ef|grep mysql或者whereis mysqldump查詢

例如我本地的就是

#!/bin/bash
time=$(date '+%Y%m%d%H%M%S')
/usr/local/mysql/bin/mysqldump -uUSERNAME -pPASSWORD DBNAME |gzip > /data/bak/DB_$time.sql.gz
find /data/bak/ -mtime +5 -name "*.gz" -exec rm -rf {} \;

mysql自動備份指令碼

#!/bin/bash

DATE=`date +%Y%m%d%H%M%S`
DATE1=`date +%Y%m%d`
DB_user=使用者
DB_password=密碼

start_time=`date +'%Y-%m-%d %H:%M:%S'`
echo "$DATE資料庫全備開始。。。。。。" >> /home/eqics/mysql_bak/logs/Full_bak_$DATE1.log
/home/eqics/mysql/bin/mysqldump --socket=/home/eqics/mysql/mysql.sockt --all-databases --default-character-set=utf8 --flush-logs -u$DB_user -p$DB_password > /home/eqics/mysql_bak/all_data/Full_Bak_$DATE.sql
if [ $? -eq 0 ]
then
	echo "$DATE資料庫備份成功......" >> /home/eqics/mysql_bak/logs/Full_Bak_$DATE1.log
cd /home/eqics/mysql_bak/all_data/
tar -zcvf Full_Bak_$DATE.sql.tar.gz Full_Bak_$DATE.sql > /dev/null
	if [ $? -eq 0 ]
	then
		echo "$DATE資料庫備份打包成功......" >> /home/eqics/mysql_bak/logs/Full_Bak_$DATE1.log
		find /home/eqics/mysql_bak/all_data/ -name "Full_Bak_*.*" -mtime +7 -exec rm -rf {} \;
		find /home/eqics/mysql_bak/logs/ -name "Full_Bak_*.log" -mtime +7 -exec rm -rf {} \;
	else
		echo "$DATE資料庫備份打包失敗......" >> /home/eqics/mysql_bak/logs/Full_Bak_$DATE1.log
		exit 0
	fi
else
	echo "$DATE資料庫備份失敗......" >> /home/eqics/mysql_bak/logs/Full_Bak_$DATE1.log
	cd /home/eqics/mysql_bak/all_data/
	rm -rf Full_Bak_$DATE.sql
	exit 0
fi

end_time=`date +'%Y-%m-%d %H:%M:%S'`
start_seconds=$(date --date="$start_time" +%s);
end_seconds=$(date --date="$end_time" +%s);
echo "本次備份執行時間: "$((end_seconds-start_seconds))"s" >> /home/eqics/mysql_bak/logs/Full_Bak_$DATE1.log
辛辛苦苦,忙忙碌碌。加油