Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/bin/bash
- ## README
- #
- # Automatic PostgreSQL backup script
- # Version: v1.0.0
- # 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.0"
- 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
- #############################
- 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"
- xz -z9e "$filename"
- echo "Completed"
- #############################
- # Backup trimming logic
- #############################
- files=$(ls -1 | grep '\.sql$' | tail -n +$4)
- filecount=$(echo -n "$files" | wc -l)
- echo "Trimming backups to $4 latest"
- echo "Will remove $filecount files"
- for i in $files
- do
- echo "Removed $i"
- rm $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
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement