Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save marcomalva/7bc5cbbc7d96cf56cbab12498b470d94 to your computer and use it in GitHub Desktop.

Select an option

Save marcomalva/7bc5cbbc7d96cf56cbab12498b470d94 to your computer and use it in GitHub Desktop.
[PostgreSQL - pg_dump schema/data of a specified list of tables only]Dump either schema or data only #psql
#!/bin/bash
#
# extract schema and then records for the tables listed in tables.lst, skipping entries starting with a #
# env var db_host, db_port, db_user and db_name control which database server/instance/role to use
#
[[ -z "${db_host}" ]] && echo "must set env var db_host. exit" && exit
[[ -z "${db_user}" ]] && echo "must set env var db_user. exit" && exit
[[ -z "${db_name}" ]] && echo "must set env var db_name. exit" && exit
# extract schema only of tables listed in tables.lst file
pg_dump -h "${db_host}" -p ${db_port:-5432} -U "${db_user}" -d "${db_name}" --schema-only $(grep -v "^#" tables.lst | awk '{print "-t "$1}' | tr "\n" " ") > "pg_dump--${db_name}--schema_only.sql"
# extract data only of tables listed in tables.lst file
pg_dump -h "${db_host}" -p ${db_port:-5432} -U "${db_user}" -d "${db_name}" --data-only $(grep -v "^#" tables.lst | awk '{print "-t "$1}' | tr "\n" " ") > "pg_dump--${db_name}--data_only.sql"
@dirkjot
Copy link
Copy Markdown

dirkjot commented May 6, 2024

Nice! you can use printf instead of print and avoid the tr

@replogle
Copy link
Copy Markdown

Or you can just do it all with awk:

${awk '! /^#/ {printf " -t "$1}' tables.lst)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment