Skip to content

Instantly share code, notes, and snippets.

@RomanGorbatko
Last active January 9, 2024 14:33
Show Gist options
  • Save RomanGorbatko/69473ff8a146bc5a9b9a23896597a233 to your computer and use it in GitHub Desktop.
Save RomanGorbatko/69473ff8a146bc5a9b9a23896597a233 to your computer and use it in GitHub Desktop.
PostgreSQL daily backup and store to Digitalocean Spaces or Amazon S3
#!/bin/bash
BACKUP_DIR=/tmp/pg_backup
DAYS_TO_KEEP=2
FILE_SUFFIX=_pg_backup.sql
DATABASE=**database-name**
USER=**database-user**
SPACE=**bucket-name**
FILE=`date +%y%m%d-%H_%M_%S`${FILE_SUFFIX}
OUTPUT_FILE=${BACKUP_DIR}/${FILE}
dumpAndZip(){
echo "Creating SQL dump"
pg_dump -U ${USER} ${DATABASE} -F p -f ${OUTPUT_FILE}
echo "Gathering files"
if gzip ${OUTPUT_FILE}; then
echo "Done gathering files"
return 0
else
echo "Failed to gather files"
return 1
fi
}
movetoSpace(){
echo "Moving to Space"
if s3cmd put --quiet ${OUTPUT_FILE}.gz s3://$SPACE; then
echo "Done moving files to s3://"$SPACE""
# prune old backups
find $BACKUP_DIR -maxdepth 1 -mtime +$DAYS_TO_KEEP -name "*${FILE_SUFFIX}.gz" -exec rm -rf '{}' ';'
return 0
else
echo "Failed to move files to the Space"
return 1
fi
}
if dumpAndZip; then
movetoSpace
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment