Skip to content

Instantly share code, notes, and snippets.

@sharmaeklavya2
Created January 24, 2016 10:00
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save sharmaeklavya2/3f54fee9ce2955f9b9fe to your computer and use it in GitHub Desktop.
Save sharmaeklavya2/3f54fee9ce2955f9b9fe to your computer and use it in GitHub Desktop.
Export all tables in a postgres database to a set of CSV files
#!/bin/bash
DB_NAME="$USER"
DBMS_SHELL="psql"
#if [ "$1" = '--help' ]; then
if [[ ( "$1" == '--help' ) || ( "$1" == '-h' ) ]]; then
echo "usage: $0 [DB_NAME] [DBMS_SHELL]"
echo "default DB_NAME is your username"
echo "default DBMS_SHELL is 'psql'"
exit 0
fi
if [ -n "$1" ]
then DB_NAME="$1"
fi
if [ -n "$2" ]
then DBMS_SHELL="$2"
fi
alias echo='>&2 echo'
mkdir -p "$DB_NAME"
echo "Fetching table list ..."
$DBMS_SHELL "$DB_NAME" -c "copy (select table_name from information_schema.tables where table_schema='public') to STDOUT;" > "$DB_NAME/tables.txt"
dbms_success=$?
if ! [ $dbms_success ]
then exit 4
fi
echo "Fetching tables ..."
readarray tables < "$DB_NAME/tables.txt"
for t in ${tables[*]}; do
$DBMS_SHELL -d "$DB_NAME" -c "copy $t to STDOUT with delimiter ',';" > "$DB_NAME/$t.csv"
done
@davidahopp
Copy link

Thanks for the gist, I added a couple of things: https://gist.github.com/davidahopp/b688aa6310dd9b1f42839108f36c968b

Include headers on export and add ability to change username used to login

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