Skip to content

Instantly share code, notes, and snippets.

@CarlosEspejo
Last active December 18, 2015 05:55
Show Gist options
  • Save CarlosEspejo/99cf381d86fb37c2b4e1 to your computer and use it in GitHub Desktop.
Save CarlosEspejo/99cf381d86fb37c2b4e1 to your computer and use it in GitHub Desktop.
Postgresql 30 day backup script
#!/bin/bash
# This script will create a compressed data dump
# that can be restored in parallel using
# pg_restore -C -j[num of cores] -d postgres 2015-09-30-app_db.dump
# note: when -C is present the db in -d is used only to make the connection.
# http://www.postgresql.org/docs/current/static/app-pgrestore.html
# http://www.postgresql.org/docs/current/static/app-pgdump.html
DATABASE_NAME=app_db
TODAY=$(date +'%Y-%m-%d')
KEEP_BACKUPS=30
BACKUP_LOCATION=/backup
cd $BACKUP_LOCATION
pg_dumpall -v --globals-only > $TODAY-globals.sql
pg_dump $DATABASE_NAME -v -F c > $TODAY-$DATABASE_NAME.dump
ls -1t *.sql | tail -n +$(($KEEP_BACKUPS+1)) | xargs rm
ls -1t *.dump | tail -n +$(($KEEP_BACKUPS+1)) | xargs rm
# To do daily data dumps for example
# run crontab -e under postgres user and add the following line
# 0 4 * * * /var/lib/postgresql/pg_backup.sh
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment