Created
March 8, 2023 11:33
-
-
Save djnnvx/1b5648d1c2e3a5681386a3891a7fa4d3 to your computer and use it in GitHub Desktop.
bash script dumping Postgresql database to separate `.csv` files (one per table) and bundling them together in a `tar` archive
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
#!/usr/bin/env bash | |
set -euo pipefail | |
POSTGRES_DB=postgres | |
POSTGRES_USER=postgres | |
CONTAINER_NAME=postgres_db_1 | |
docker exec "${CONTAINER_NAME}" psql -U "$POSTGRES_USER" \ | |
-d "$POSTGRES_DB" -Atc "select schema_name from information_schema.schemata" |\ | |
while read -r SCHEMA; do | |
if [[ "$SCHEMA" != "pg_catalog" && "$SCHEMA" != "information_schema" ]]; then | |
echo "[+] Dumping ${SCHEMA} to .csv" | |
docker exec "${CONTAINER_NAME}" psql -U "$POSTGRES_USER" \ | |
-d "$POSTGRES_DB" -Atc "select tablename from pg_tables where schemaname='$SCHEMA'" |\ | |
while read -r TBL; do | |
echo " -> dumping ${TBL}..." | |
docker exec "${CONTAINER_NAME}" psql -U "$POSTGRES_USER" -d "${POSTGRES_DB}" \ | |
-c "COPY $SCHEMA.$TBL TO STDOUT WITH CSV DELIMITER ';' HEADER ENCODING 'UTF-8'" > "${SCHEMA}"."${TBL}".csv | |
done | |
echo "[+] Done." | |
fi | |
done | |
FILENAME=csv-export-$(date +%d-%m-%Y).tar | |
echo "[+] Bundling dumps to ${FILENAME}" | |
tar -cvf csv-export"$(date +%d-%m-%Y)".tar ./*.csv | |
echo "--== DONE ==--" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment