自動備份數據庫shell腳本

- 定時備份PG數據庫

[root@localhost ~]# vim dump.sh
#!/bin/bash
#這裏可以定義你的庫名
database1=database1
database2=database2
#這裏可以定義你的備份文件的路徑以及格式
DirPath1=/opt/bak1/
DirPath2=/opt/bak2/
filename=$(date +%Y-%m-%d).sql.gz
#備份database1
if [ ! -d ${DirPath1} ];then
    mkdir ${DirPath1}
fi
PGPASSWORD=123456 /opt/PostgreSQL/9.6/bin/pg_dump -h 127.0.0.1 -U postgres -a $database1 | gzip > $DirPath1/$filename
if [ $? -ne 0 ];then
    echo "`date +%F" "%H:%M:%S` -----> Database ${database1} backup failed."
else
    echo "`date +%F" "%H:%M:%S` -----> Database ${database1} backup successfully."
sleep 2
    echo "`date +%F" "%H:%M:%S` -----> Database ${database1} backup completed."
fi
sleep 3
#刪除數據庫7天之前的備份文件
cd ${DirPath1}
if [ $? -eq 0 ];then
    find ${DirPath1} -mtime +7 -exec rm -f {} \;  #要寫絕對路徑,防止誤刪
    echo "Delete the backup files from the ${database1} library 7 days ago."
fi
sleep 2
#備份database2
if [ ! -d ${DirPath2} ];then
    mkdir ${DirPath2}
fi
PGPASSWORD=123456 /opt/PostgreSQL/9.6/bin/pg_dump -h 127.0.0.1 -U postgres -a -T sys_log $database2 | gzip > $DirPath2/$filename
if [ $? -ne 0 ];then
    echo "`date +%F" "%H:%M:%S` -----> Database ${database2} backup failed."
else
    echo "`date +%F" "%H:%M:%S` -----> Database ${database2} backup  successfully."
sleep 2 
    echo "`date +%F" "%H:%M:%S` -----> Database ${database2} backup completed."
fi
sleep 3
#刪除數據庫7天之前的備份文件
cd ${DirPath2}
if [ $? -eq 0 ];then
    find ${DirPath2} -mtime +7 -exec rm -f {} \;  #要寫絕對路徑,防止誤刪
    echo "Delete the backup files from the ${database2} library 7 days ago."
fi
- 備份參數說明
-a 		只導出數據,不包括模式
-s 		只導出結構,不包括數據
-T 		不轉儲指定名稱的表
- 每天的晚上12點開始備份
[root@localhost ~]# crontab -e
0 24 * * *      /root/dump.sh
- 重啓服務
[root@localhost ~]# service crond restart
- 恢復數據
  1. 備份數據庫結構
[root@localhost ]# /opt/PostgreSQL/9.6/bin/pg_dump -h 127.0.0.1 -U postgres -s -T sys_log database1 > /opt/bak1/structure.sql
  1. 恢復數據庫結構
[root@localhost ]# /opt/PostgreSQL/9.6/bin/psql  -U postgres -d test < /opt/bak1/structure.sql
  1. 恢復數據庫數據
[root@localhost ]# gunzip -c /opt/bak1/2020-04-02.sql.gz | /opt/PostgreSQL/9.6/bin/psql -U postgres -d test

備註:-U指定用戶名,-d指定庫名

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章