Skip to content

Instantly share code, notes, and snippets.

@duckworth
Last active August 16, 2019 13:46
Show Gist options
  • Save duckworth/30ee45ea5b82001341dbd38d1ae1abb3 to your computer and use it in GitHub Desktop.
Save duckworth/30ee45ea5b82001341dbd38d1ae1abb3 to your computer and use it in GitHub Desktop.
basic pgbackup and pgrestore command utlitites used during local development to quickly save and restore local databases
#!/bin/bash
backupdir="$HOME/dbbackups";
day=`date -u +"%Y-%m-%d"`;
mkdir -p $backupdir/$day;
echo "PostgreSQL Backup util on $HOSTNAME";
echo "================================="
echo `date`;
for database in `/usr/local/bin/psql -lt | awk '{print $1}' | grep -vE '\||^$|template[0-9]'`;
do
printf "Dumping $database...\n"
name=$backupdir/$day/$database
if [[ -e $name.sql.gz ]] ; then
i=2
while [[ -e $name.$i.sql.gz ]] ; do
let i++
done
name=$name.$i
fi
/usr/local/bin/pg_dump -c $database | gzip -c > $name.sql.gz;
printf "Backup created $name.sql.gz\n"
#/bin/chmod 600 &name;
done
echo "Done. $(date)";
exit 0;
#!/bin/bash
backupdir="$HOME/dbbackups";
echo "PostgreSQL Restore util on $HOSTNAME";
echo "================================="
echo `date`;
echo
cd "$backupdir"
printf "Please select folder with backups:\n"
select d in */; do test -n "$d" && break; echo ">>> Invalid Selection"; done
cd "$d" && pwd
printf "Please select backup:\n"
select f in *.sql.gz; do test -n "$f" && break; echo ">>> Invalid Selection"; done
fileExt=${f#*.}
dbname=${f%*.$fileExt}
echo "Drop $dbname and restore from $f ?"
read -p "Are you sure? Enter y to proceed: " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]
then
dropdb "$dbname"
createdb "$dbname"
gunzip < "$f" | psql "$dbname"
fi
echo "$dbname restored"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment