Skip to content

Instantly share code, notes, and snippets.

@repodevs
Forked from sirbrillig/pgsql_backup.sh
Created May 18, 2019 19:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save repodevs/92aee1bffbd42b9b15c6af7bad118a25 to your computer and use it in GitHub Desktop.
Save repodevs/92aee1bffbd42b9b15c6af7bad118a25 to your computer and use it in GitHub Desktop.
Postgresql daily backup script.
#!/bin/bash
#
# Backup a Postgresql database into a daily file.
#
BACKUP_DIR=/pg_backup
DAYS_TO_KEEP=14
FILE_SUFFIX=_pg_backup.sql
DATABASE=
USER=postgres
FILE=`date +"%Y%m%d%H%M"`${FILE_SUFFIX}
OUTPUT_FILE=${BACKUP_DIR}/${FILE}
# do the database backup (dump)
# use this command for a database server on localhost. add other options if need be.
pg_dump -U ${USER} ${DATABASE} -F p -f ${OUTPUT_FILE}
# gzip the mysql database dump file
gzip $OUTPUT_FILE
# show the user the result
echo "${OUTPUT_FILE}.gz was created:"
ls -l ${OUTPUT_FILE}.gz
# prune old backups
find $BACKUP_DIR -maxdepth 1 -mtime +$DAYS_TO_KEEP -name "*${FILE_SUFFIX}.gz" -exec rm -rf '{}' ';'
@repodevs
Copy link
Author

repodevs commented Aug 15, 2019

Dump Database without ownership

$ pg_dump --format=c --clean --no-owner --no-privileges -U DBUSER -W -h 127.0.0.1 -d DB_NAME > DB_NAME.dump

Restore Database

$ pg_restore -d dbname filename

https://www.postgresql.org/docs/current/backup-dump.html

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