Skip to content

Instantly share code, notes, and snippets.

@kcleong
Created December 3, 2024 13:52
Show Gist options
  • Save kcleong/9522c4b8477d5a0ef145a0a1e1cba24a to your computer and use it in GitHub Desktop.
Save kcleong/9522c4b8477d5a0ef145a0a1e1cba24a to your computer and use it in GitHub Desktop.
Postgres backups
#!/bin/bash
while getopts c:p: flag
do
case "${flag}" in
p) port=${OPTARG};;
c) cluster=${OPTARG};;
esac
done
if [ -z $port ]; then
port=5432;
fi
if [ -z $cluster ]; then
cluster="11/main";
fi
# Location to place backups.
backup_dir="/var/backups/postgres/"
# String to append to the name of the backup files
#backup_date=`date +%d-%m-%Y`
backup_date=`date +%Y-%m-%d_%H-%M`
# Numbers of days you want to keep copie of your databases
# NOTE THAT WE DONT NEED MANY DAYS SINCE WE HAVE A BACKUP MACHINE
number_of_days=3
databases=`psql -p $port -l -t | cut -d'|' -f1 | sed -e 's/ //g' -e '/^$/d'`
for i in $databases; do
if [ "$i" != "template0" ] && [ "$i" != "template1" ]; then
echo Dumping $i to $backup_dir$i\_$backup_date
pg_dump --cluster $cluster -p $port -Fc $i > $backup_dir$i\_$backup_date
fi
done
find $backup_dir -type f -prune -mtime +$number_of_days -exec rm -f {} \;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment