Skip to content

Instantly share code, notes, and snippets.

@develpudu
Forked from devjaime/postgresql_export.sh
Created March 21, 2025 18:03
Show Gist options
  • Select an option

  • Save develpudu/809330a2b551c80b96aff10ec12360a3 to your computer and use it in GitHub Desktop.

Select an option

Save develpudu/809330a2b551c80b96aff10ec12360a3 to your computer and use it in GitHub Desktop.
Automatizando Exportaciones de PostgreSQL con Bash
#!/bin/bash
# Configuration variables
DB_HOST="localhost" # Database host
DB_PORT="5432" # Database port
DB_NAME="database_name" # Database name
DB_USER="db_user" # Database user
DB_PASSWORD="" # Database password (leave empty if using .pgpass)
TABLE_NAME='"table_name"' # Table to export
OUTPUT_FILE="table_export_$(date +%Y%m%d).sql" # Output file with dynamic date
# Check if the output file already exists
if [ -f "$OUTPUT_FILE" ]; then
echo "The file $OUTPUT_FILE already exists. Do you want to overwrite it? (y/n)"
read -r RESPONSE
if [ "$RESPONSE" != "y" ]; then
echo "Operation canceled."
exit 1
fi
fi
# Generate the table dump
PGPASSWORD="$DB_PASSWORD" pg_dump --host="$DB_HOST" \
--port="$DB_PORT" \
--username="$DB_USER" \
--dbname="$DB_NAME" \
--table="$TABLE_NAME" \
--data-only \
--file="$OUTPUT_FILE"
# Check if the operation was successful
if [ $? -eq 0 ]; then
echo "The dump of table $TABLE_NAME has been successfully created in $OUTPUT_FILE."
else
echo "An error occurred while generating the dump. Please check the parameters and try again."
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment