需求臨近年關整理一些指令碼程式,發現一個mysqlDatabase Backup的指令碼可以和大家分享一下,基於環境是ubuntu10.04server思路
- 擷取mysql伺服器所有資料庫名稱,過濾掉不需要備份的資料庫
- 通過mysqldump來for迴圈匯出所有的資料庫的sql檔案
- 用zip加密壓縮所有的sql檔案
- 定期進行資料清理工作
shell代碼資料庫匯出代碼
#!/bin/bash#1.資料庫資訊定義mysql_host="192.168.1.1"mysql_user="root"mysql_passwd="root"#sql備份目錄root_dir="/backup"back_dir="/backup/databases"data_dir="databases"store_dir="database"if [ ! -d $back_dir ]; thenmkdir -p $back_dirfi#備份的資料庫數組db_arr=$(echo "show databases;" | mysql -u$mysql_user -p$mysql_passwd -h$mysql_host)#不需要備份的單例資料庫nodeldb="test1"#當前日期date=$(date -d '+0 days' +%Y%m%d)#zip打包密碼zippasswd="passwd"zipname="lczh_"$date".zip"#2.進入到備份目錄cd $back_dir#3.迴圈備份for dbname in ${db_arr}doif [ $dbname != $nodeldb ]; thensqlfile=$dbname-$date".sql"mysqldump -u$mysql_user -p$mysql_passwd -h$mysql_host $dbname >$sqlfilefidone#4.tar打包所有的sql檔案tar -zcPpf $root_dir/$store_dir/$zipname --directory / $root_dir/$data_dir#打包成功後刪除sql檔案if [ $? = 0 ]; thenrm -r $data_dirfi資料定期清理指令碼
作用定期清理14天前的備份檔案shell代碼
#!/bin/bash - #1.參數配置#mysql檔案備份目錄backup_dir1="/backup/test1/"backup_dir2="/backup/test2/"backdir_arr=($backup_dir1 $backup_dir2)#到期檔案的時間keep_time=14#當前所在星期,crontab在奇數的星期7執行week=$(date +%W)flag=`expr $week % 2`#2.清理到期檔案,只在奇數星期7執行if [ $flag -eq 1 ]; thenfor dir in ${backdir_arr[*]}doif [ -d $dir ]; then#尋找14天之外的檔案資料clean_arr=`find $dir -type f -mtime +$keep_time -exec ls {} \;`for cleanfile in ${clean_arr}dorm $cleanfiledonefidonefi
crontab配置
0 5 * * 7 執行清理指令碼
後記大家有更好的Database Backup方法或者是指點我shell指令碼的不足,都可以跟帖留言,我保證回複,一起加油!