Skip to content

Instantly share code, notes, and snippets.

@flipbit03
Last active March 24, 2024 19:53
Show Gist options
  • Select an option

  • Save flipbit03/27d32a5ac7970e610cf085071df73e0e to your computer and use it in GitHub Desktop.

Select an option

Save flipbit03/27d32a5ac7970e610cf085071df73e0e to your computer and use it in GitHub Desktop.
Dump from a PG database, using Docker to use the exact version
#!/bin/bash
# Function to check if an environment variable is set
check_env_variable() {
local var_name="$1"
local var_desc="$2"
if [ -z "${!var_name}" ]; then
echo "Error: '${var_name}' environment variable is not set. Please set it to ${var_desc}."
exit 1
fi
}
# Check required environment variables
check_env_variable "PG_VERSION" "specify the PostgreSQL version"
check_env_variable "DB_USER" "specify the database user"
check_env_variable "DB_PASSWORD" "specify the database password"
check_env_variable "DB_HOST" "specify the database host"
check_env_variable "DB_PORT" "specify the database port"
check_env_variable "DB_NAME" "specify the database name"
# Get current user's ID and group ID
CURRENT_UID=$(id -u)
CURRENT_GID=$(id -g)
# Define timestamp format
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
# Run the PostgreSQL container to dump the database
docker run \
--rm \
--volume=$(pwd):/host \
-e PGPASSWORD="$DB_PASSWORD" \
-e CURRENT_UID="$CURRENT_UID" \
-e CURRENT_GID="$CURRENT_GID" \
--user="$CURRENT_UID:$CURRENT_GID" \
--network host \
postgres:${PG_VERSION} \
pg_dump -v -U "$DB_USER" -h "$DB_HOST" -p "$DB_PORT" -d "$DB_NAME" -Fc -f "/host/dump_${TIMESTAMP}.dump"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment