Skip to content

Instantly share code, notes, and snippets.

@yuryroot
Last active October 5, 2016 13:35
Show Gist options
  • Save yuryroot/7bb89a286f0b840c6ee5 to your computer and use it in GitHub Desktop.
Save yuryroot/7bb89a286f0b840c6ee5 to your computer and use it in GitHub Desktop.
Bash script for backup Postgresql cluster
#!/usr/bin/env bash
# These ENV variables should be specified:
# * WORKING_DIR
# * PG_USER
# * SCP_USER
# * SCP_HOST
# * SCP_DIR
#
# Also optional variable MAIL_TO can be specified.
#
# For example:
# WORKING_DIR=/tmp/db_backup/ PG_USER=postgres SCP_USER=name SCP_HOST=localhost SCP_DIR=uploads ./db_backup.sh
# [email protected] WORKING_DIR=/tmp/db_backup/ PG_USER=postgres SCP_USER=name SCP_HOST=localhost SCP_DIR=uploads ./db_backup.sh
TIMESTAMP=$(date +%Y_%m_%d)
BACKUP_NAME="${TIMESTAMP}_pg_basebackup"
ARCHIVE_NAME="$BACKUP_NAME.tar.gz"
SPLIT_NAME_PREFIX="${ARCHIVE_NAME}_"
SPLIT_SIZE="10G"
log() {
echo "[$(date)] $1"
}
exit_unless_success() {
exit_code=$?
if [ $exit_code -ne 0 ]; then
send_mail "[$BACKUP_NAME] An unknown error occurred while creating backup. Exit code: $exit_code"
exit $exit_code
fi
}
send_mail() {
if [ -n "$MAIL_TO" ]; then
log "Sending email to $MAIL_TO..."
mail -s "$1" $MAIL_TO < /dev/null
fi
}
if [ ! -d "$WORKING_DIR" ]; then
mkdir -p "$WORKING_DIR"
exit_unless_success
fi
cd $WORKING_DIR
log "Creating basebackup..."
pg_basebackup -U $PG_USER --pgdata=$BACKUP_NAME --xlog-method=stream
exit_unless_success
log "Compressing backup..."
tar -czf $ARCHIVE_NAME $BACKUP_NAME
exit_unless_success
log "Splitting archive by parts of $SPLIT_SIZE..."
split -b $SPLIT_SIZE $ARCHIVE_NAME $SPLIT_NAME_PREFIX
exit_unless_success
log "Uploading to remote server..."
scp $SPLIT_NAME_PREFIX* $SCP_USER@$SCP_HOST:$SCP_DIR
exit_unless_success
log "Cleaning..."
rm -rf $BACKUP_NAME*
exit_unless_success
send_mail "[$BACKUP_NAME] Database backup was successfully created."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment