scripts/postgresql_backup/pg_backup.sh

39 lines
1.2 KiB
Bash
Raw Normal View History

2024-11-06 17:51:27 +00:00
#!/bin/bash
2024-11-06 17:55:49 +00:00
# Load environment variables from .env file
if [ -f .env ]; then
export $(grep -v '^#' .env | xargs)
else
echo ".env file not found! Please create it with the necessary configuration."
exit 1
fi
2024-11-06 17:51:27 +00:00
2024-11-06 17:55:49 +00:00
# Set file extension based on DUMP_FORMAT
EXTENSION="dump" # Default extension for custom format
2024-11-06 17:51:27 +00:00
if [[ "$DUMP_FORMAT" == "sql" ]]; then
EXTENSION="sql.gz"
fi
# Create backup directory if it doesn't exist
mkdir -p "$BACKUP_PATH"
# Get a list of all databases, excluding template databases
DATABASES=$(psql -h "$HOST" -p "$PORT" -U "$USER" -d postgres -t -c "SELECT datname FROM pg_database WHERE datistemplate = false;")
# Loop over each database and create a backup
for DB in $DATABASES; do
BACKUP_FILE="$BACKUP_PATH/$DB.$EXTENSION"
if [[ "$DUMP_FORMAT" == "custom" ]]; then
# Create a compressed custom-format backup
pg_dump -h "$HOST" -p "$PORT" -U "$USER" -Fc "$DB" -f "$BACKUP_FILE"
elif [[ "$DUMP_FORMAT" == "sql" ]]; then
# Create a plain-text SQL backup and compress it with gzip
pg_dump -h "$HOST" -p "$PORT" -U "$USER" "$DB" | gzip > "$BACKUP_FILE"
else
echo "Invalid DUMP_FORMAT specified: $DUMP_FORMAT"
exit 1
fi
echo "Backup for database '$DB' created at '$BACKUP_FILE'"
done