Skip to content

Instantly share code, notes, and snippets.

@t0rik
Forked from powellc/pg_backup_all.sh
Created June 13, 2023 09:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save t0rik/651a2e1e8fa8484ddb9102b5f7e604e0 to your computer and use it in GitHub Desktop.
Save t0rik/651a2e1e8fa8484ddb9102b5f7e604e0 to your computer and use it in GitHub Desktop.
Bash script to backup all postgresql databases on a server, run with cron once a day or 5 times a day, whatever. Just updated it so it ignores your postgres db, and also bzips the backups and adds a symlink to a latest directory. Sweet.
#!/bin/bash
# Location to place backups.
backup_dir="/var/backups/databases/"
nightly_dir="/var/backups/databases/latest/"
#String to append to the name of the backup files
backup_date=`date +%d-%m-%Y`
#Numbers of days you want to keep copie of your databases
number_of_days=15
databases=`psql -l -t | cut -d'|' -f1 | sed -e 's/ //g' -e '/^$/d'`
for i in $databases; do if [ "$i" != "postgres" ] && [ "$i" != "template0" ] && [ "$i" != "template1" ] && [ "$i" != "template_postgis" ]; then
echo Dumping $i to $backup_dir$i\_$backup_date.sql
pg_dump $i > $backup_dir$i\_$backup_date.sql
bzip2 $backup_dir$i\_$backup_date.sql
ln -fs $backup_dir$i\_$backup_date.sql.bz2 $nightly_dir$i-nightly.sql.bz2
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