Postgresql backup all databases seperate files

Situtation: We need backup all postgresql database local before moving to other computer. But we want 1 file dump per 1 database

Solution:

  • Create bash file
#!/bin/sh
DBLIST=`/usr/local/bin/psql -U acvq -d postgres -q -t -c 'SELECT
datname from pg_database order by datname'`
for d in $DBLIST
do
     echo "db = $d";
     pg_dump -U acvq $d > ./$d.sql
done

  • To restore to other local machine
#!/bin/sh
DBLIST=`ls ./DB_PG`
for d in $DBLIST
do
 name=$(echo "$d" | cut -f 1 -d '.')
#  createdb $name
  psql -f ./DB_PG/$d $name
done

References:

Tagged with devops