Skip to content

Instantly share code, notes, and snippets.

@mrsarm
Created December 15, 2014 19:00
Show Gist options
  • Save mrsarm/d2d925078cbfcaae7e8e to your computer and use it in GitHub Desktop.
Save mrsarm/d2d925078cbfcaae7e8e to your computer and use it in GitHub Desktop.
Script to backup PostgreSQL with Barman
#!/bin/bash
#
# Script to backup PostgreSQL with Barman.
#
# After the backup is performed, this script
# also delete the oldest backup found.
#
# See the `PG Barman` home page for more information:
# http://www.pgbarman.org
#
# Author: (2014) Mariano Ruiz <mrsarm@gmail.com>
#
# Duplicity command line options
BARMAN_OPTS=""
# Database instance to backup
DATABASE="main"
# Log file
LOG="/var/log/backup-pgbarman-$DATABASE.log"
# Date format printed into the log
DATE_FORMAT="+%Y-%m-%d %T"
echo "`date "$DATE_FORMAT"` INFO : Starting to backup '$DATABASE' databases ... " 2>&1 | tee -a $LOG
T_START=$(date +%s) # To calculate the process time
barman backup $BARMAN_OPTS $DATABASE 2>&1 | tee -a $LOG
EXIT_CODE=${PIPESTATUS[0]}
T_DIFF=$(( $(date +%s) - $T_START ))
if [ "$EXIT_CODE" != "0" ]; then
echo "`date "$DATE_FORMAT"` ERROR : ... Backup from '$DATABASE' databases done with errors (elapsed time `date -u -d @"$T_DIFF" +'%-Hh %-Mm %-Ss'`). Check the log above." 2>&1 | tee -a $LOG
exit -1
fi
echo "`date "$DATE_FORMAT"` INFO : Starting to delete oldest backup from '$DATABASE' databases ... " 2>&1 | tee -a $LOG
barman delete $DATABASE oldest 2>&1 | tee -a $LOG
EXIT_CODE=${PIPESTATUS[0]}
T_DIFF=$(( $(date +%s) - $T_START ))
if [ "$EXIT_CODE" != "0" ]; then
echo "`date "$DATE_FORMAT"` ERROR : ... Deleting oldest backup from '$DATABASE' databases done with errors (elapsed time `date -u -d @"$T_DIFF" +'%-Hh %-Mm %-Ss'`). Check the log above." 2>&1 | tee -a $LOG
exit -1
fi
echo "`date "$DATE_FORMAT"` INFO : ... Backup from '$DATABASE' databases done at `date -u -d @"$T_DIFF" +'%-Hh %-Mm %-Ss'`." 2>&1 | tee -a $LOG
exit 0
@guillermogfer
Copy link

Hi Mariano, this script looks pretty cool and fits almost what I need and I've been searching for.
Thanks for sharing!

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