shell指令碼備份mysql資料庫

來源:互聯網
上載者:User
需求臨近年關整理一些指令碼程式,發現一個mysqlDatabase Backup的指令碼可以和大家分享一下,基於環境是ubuntu10.04server思路
  1. 擷取mysql伺服器所有資料庫名稱,過濾掉不需要備份的資料庫
  2. 通過mysqldump來for迴圈匯出所有的資料庫的sql檔案
  3. 用zip加密壓縮所有的sql檔案
  4. 定期進行資料清理工作
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指令碼的不足,都可以跟帖留言,我保證回複,一起加油!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.