Skip to content

Instantly share code, notes, and snippets.

@lalmazari
Created May 23, 2024 09:02
Show Gist options
  • Save lalmazari/a6dee3786bf53b7ef74ea0f320e55a77 to your computer and use it in GitHub Desktop.
Save lalmazari/a6dee3786bf53b7ef74ea0f320e55a77 to your computer and use it in GitHub Desktop.
This Bash script automates the backup of PostgreSQL databases. It takes backups of specified databases and stores them in a timestamped directory.
#!/bin/bash
# Database connection information
DB_HOST=""
DB_PORT=""
DB_USER=""
DB_PASSWORD=""
# Get current timestamp
TIMESTAMP=$(date +"%d.%m.%Y")
# Create a backup directory
BACKUP_DIR="postgresql_backup_${TIMESTAMP}"
mkdir "$BACKUP_DIR"
# Array of databases to backup
DATABASES_TO_BACKUP=("DB_NAME1" "DB_NAME2")
# Loop through each specified database and take backup
for DB_NAME in "${DATABASES_TO_BACKUP[@]}"
do
# Generate backup file name with database name and timestamp
BACKUP_FILE="${DB_NAME}.dump"
# Take Backup using pg_dump with password
PGPASSWORD="$DB_PASSWORD" pg_dump -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$DB_NAME" -F c -f "${BACKUP_DIR}/${BACKUP_FILE}"
echo "Backup for database $DB_NAME completed successfully. Backup file: ${BACKUP_DIR}/${BACKUP_FILE}"
done
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment