PostgreSQL 通用备份脚本

#!/bin/bash
 
PG_USER="postgres"
SUDO_CMD=$(which sudo)
SUDO="$SUDO_CMD -u $PG_USER"
PSQL_CMD=$(which psql)
PSQL="$SUDO $PSQL_CMD"
GREP=$(which grep)
AWK=$(which awk)
PGDUMP_CMD=$(which pg_dump)
PGDUMP="$SUDO $PGDUMP_CMD"
VACUUM_CMD=$(which vacuumdb)
VACUUM="$SUDO $VACUUM_CMD"
FIND=$(which find)
 
# Bellow is how old, in days, a backup will need to be deleted.
# This helps cleaning up and don't keep piling backups
MAX_DAYS=10
 
# 备份文件存放路径,如果不存在需要创建
BACKUPS_DIR="/var/backups/pgdbs"
 
# To get a list of all databases uncomment the following 3 lines
#DBS=$($PSQL -q -c "\l" | sed -n 4,/\eof/p | grep -v rows\) | grep -v template0 | grep -v template1 | awk {'print $1'} | grep -v :)
#echo $DBS
#exit
 
# Uncomment bellow to backup all databases
#DBS=$($PSQL -q -c "\l" | sed -n 4,/\eof/p | grep -v rows\) | grep -v template0 | grep -v template1 | awk {'print $1'} | grep -v :)
 
#要备份的数据库名称,一次可备份多个数据库,使用空格将他们的名称分开
DBS="postgres" #替换成要备份的数据库名
    
for DB in $DBS
    do
        echo -n "Vacuum'ing database $DB ... "
        $($VACUUM -z $DB)
        echo "Done."
        BACKUP_NAME="$BACKUPS_DIR/$DB-backup-$(date +%Y%m%d%H%M).sql.tar.bz2"
        echo -n "Creating backup of database $DB ... "
        $($PGDUMP -Ft -b -o $DB | bzip2 --best > $BACKUP_NAME)
        echo "Done."
        echo -n "Removing backups of database $DB older than $MAX_DAYS days ... "
        $($FIND $BACKUPS_DIR -name "$DB*" -type f -mtime +$MAX_DAYS -delete)
        echo "Done."
  done
 

 

一个通用的 PostgreSQL 数据库定时备份脚本,加入 Unix/Linux 的 crontab 中即可:

 

你可能感兴趣的:(PostgreSQL)