Created
March 19, 2025 11:39
-
-
Save devjaime/cc71396d034ff4cbee76bd1ea02dce80 to your computer and use it in GitHub Desktop.
Automatizando Exportaciones de PostgreSQL con Bash
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/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