k43D/postgres_backup/backup-script.sh
2023-12-27 20:12:42 +01:00

41 lines
2.1 KiB
Bash

#!/bin/bash
# Set default values
PG_USER=${PG_USER:-postgres}
PG_PASSWORD=${PG_PASSWORD:-postgres}
PG_HOST=${PG_HOST:-localhost}
PG_PORT=${PG_PORT:-5432}
# Set backup directory
BACKUP_DIR="/backup/"
# Generate backup timestamp with format "YYYY-MM-DD_HH-MM-SS"
TIMESTAMP=$(date +"%Y-%m-%d_%H-%M-%S")
# Set backup file name with timestamp
BACKUP_FILE="${BACKUP_DIR}/pg_dump_all_${TIMESTAMP}.sql.gz"
# Dump all databases to backup file
pg_dumpall --clean --if-exists --username="${PG_USER}" --host="${PG_HOST}" --port="${PG_PORT}" | gzip >"${BACKUP_FILE}"
# Rename backups that are old enough to weekly, monthly, or yearly
find $BACKUP_DIR -maxdepth 1 -type f -name "*.gz" -not -name "*weekly*" \
-not -name "*monthly*" -not -name "*yearly*" \
-mtime +7 -mtime -28 -exec mv -f {} ${BACKUP_DIR}/pg_dump_all_weekly.sql.gz \; # move daily backups older than 7 days to weekly backups
find $BACKUP_DIR -maxdepth 1 -type f -name "*.gz" -not -name "*monthly*" \
-not -name "*yearly*" -mtime +28 -mtime -365 \
-exec mv -f {} ${BACKUP_DIR}/pg_dump_all_monthly.sql.gz \; # move weekly backups older than 28 days to monthly backups
find $BACKUP_DIR -maxdepth 1 -type f -name "*.gz" -not -name "*yearly*" \
-mtime +365 -exec mv -f {} ${BACKUP_DIR}/pg_dump_all_yearly.sql.gz \; # move monthly backups older than 365 days to yearly backups
# Clean up backups older than retention periods
find $BACKUP_DIR -maxdepth 1 -type f -name "*.gz" \
-mtime +7 -mtime -28 -not -name "*weekly*" -not -name "*monthly*" -exec rm -f {} + # remove daily backups older than 7 days but exclude those that are weekly or monthly backups
find $BACKUP_DIR -maxdepth 1 -type f -name "*.gz" \
-mtime +28 -mtime -365 -not -name "*monthly*" -not -name "*yearly*" -exec rm -f {} + # remove weekly backups older than 28 days but exclude those that are monthly or yearly backups
find $BACKUP_DIR -maxdepth 1 -type f -name "*.gz" \
-mtime +365 -not -name "*yearly*" -exec rm -f {} + # remove monthly backups older than 365 days but exclude those that are yearly backups
# Print confirmation message
echo "Done. Backup file: ${BACKUP_FILE}"