Type Slowly

Jun 8

Automatically backing up a postgres database

I’ve got a web server I’m looking after that has a postgres database with some important information in it. The server’s filesystem itself is backed up nightly, but I want to make sure that there’s a dump of the database on disk before this happens. This clearly requires a cron job, and the use of the pg_dump command. However, I’ve got a few other requirements: I need backups for the last n days to be stored and automatically rotated, and the backups should be gzipped for storage. The result is this handly little bash script:

#!/usr/bin/env bash
DATABASE_NAME=somedatabase
BACKUP_PATH=/path/to/backup/dir
BACKUP_LIMIT=7
pg_dump $DATABASE_NAME | gzip -c > "$BACKUP_PATH"/"$DATABASE_NAME"_`date +"%Y%m%d%H%M"`.sql.gz
BC=$(ls $BACKUP_PATH | wc -l)
if [ "$BC" -ge "$BACKUP_LIMIT" ]; then
    ls -t $BACKUP_PATH | tail -$(($BC-$BACKUP_LIMIT)) | xargs -I{} rm $BACKUP_PATH/{}
fi

blog comments powered by Disqus
Page 1 of 1