Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to easily backup PostreSQL database. This script automatically deletes old backups
#!/bin/bash
CURRDATE=`date +%Y_%m_%d-%H_%M`
SERVERNAME="localhost"
BAK_FILE=/path/to/backups/$SERVERNAME-production-sql-$CURRDATE.sql.gz # change the PATH here
DB_HOST="localhost"
DB_NAME="DB_NAME_HERE" # Change this
function quit {
ERROR_CODE=$1
ERROR_MSG=$2
echo $ERROR_MSG
exit $ERROR_CODE
}
cd /tmp
su -c "pg_dump $DB_NAME" postgres | gzip > $BAK_FILE
RESULT=$?
if [ "$RESULT" -ne "0" ]; then
quit 1 "ERROR: Cannot backup database : $RESULT"
fi
# Delete old (older than 14 days from now) backups
find /path/to/backups/*.sql.gz -mtime +14 -exec rm {} \; # change the PATH here
quit 0 ""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.