#!/bin/bash # Configuration BACKUP_DIR="/var/lib/postgresql_archive/pg_dumpfiles" TIMESTAMP=$(date +%Y%m%d_%H%M%S) RETENTION_DAYS=7 # Ensure directory exists mkdir -p "$BACKUP_DIR" # Get all non-system databases and back each one up. psql -U postgres -d postgres -Atc "SELECT datname FROM pg_database WHERE datistemplate = false AND datname <> 'postgres' ORDER BY datname" | while IFS= read -r DB_NAME; do pg_dump -U postgres -d "$DB_NAME" | gzip > "$BACKUP_DIR/${DB_NAME}_$TIMESTAMP.sql.gz" echo "Backup completed: ${DB_NAME}_$TIMESTAMP.sql.gz" done # Delete backups older than retention period find "$BACKUP_DIR" -type f -mtime +$RETENTION_DAYS -delete