Last active
September 16, 2017 20:56
-
-
Save Emzi0767/9f18fdd49ac66d72ac2976086cf85bc8 to your computer and use it in GitHub Desktop.
PostgreSQL backup script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
## README | |
# | |
# Automatic PostgreSQL backup script | |
# Version: v1.0.5 | |
# Author: Emzi0767 | |
# Usage: | |
# ./backup_db.sh <database> <username> <password> <max_count> | |
# | |
# Use with cron. This script will automatically backup your | |
# PostgreSQL database, compress the backup | |
NAME="Automatic PostgreSQL backup script" | |
VERSION="v1.0.5" | |
AUTHOR="Emzi0767" | |
USAGE="./backup_db.sh <database> <username> <password> <max_count>" | |
do_backup() { | |
echo "Beginning database backup..." | |
############################# | |
# Backup initialisation logic | |
############################# | |
targetdir="/home/emzi0767/dat/db_backups/$1" | |
# Check if the directory doesn't exist, and if it doesn't, create it | |
if [ ! -d "$targetdir" ] | |
then | |
echo "Target directory ($targetdir) doesn't exist, creating" | |
mkdir "$targetdir" | |
fi | |
# Enter the target directory | |
cd "$targetdir" | |
############################# | |
# Postgres backup logic | |
############################# | |
# Format the filename | |
filename="$1_$(date +%s).sql" | |
echo "Database: $1" | |
echo "Username: $2" | |
echo "Target: $filename" | |
# Dump the database | |
PGPASSWORD="$3" pg_dump -U "$2" -d "$1" > "$filename" | |
echo "Postgres dump completed, compressing" | |
# Compress the backup | |
xz -z9e "$filename" | |
echo "Completed" | |
############################# | |
# Backup trimming logic | |
############################# | |
# Find the oldest backups and count them | |
files=$(ls -1t | grep '\.sql\.xz$' | tail -n +$(($4 + 1))) | |
filecount=$(echo -n "$files" | wc -l) | |
filecount=$(($filecount + 1)) | |
echo "Trimming backups to $4 latest" | |
echo "Will remove $filecount files" | |
# Remove the oldest backups | |
for i in $files | |
do | |
rm $i | |
echo "Removed $i" | |
done | |
echo "Backups trimmed" | |
} | |
print_usage() { | |
echo "$NAME $VERSION by $AUTHOR" | |
echo "Usage:" | |
echo " $USAGE" | |
} | |
if [ "$1" == "--help" ] || [ "$1" == "-h" ] | |
then | |
print_usage | |
elif [ -z "$1" ] || [ -z "$2" ] || [ -z "$3" ] || [ -z "$4" ] | |
then | |
print_usage | |
else | |
do_backup "$1" "$2" "$3" "$4" | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment