Bash – Automate pg_dump in a bash script

backupbashdatabase-backuppostgresql

I am re-learning bash after years of not using it very much and need to figure out a way to automate pg_dump of a single database to a directory.

Currently I manually ssh into the box, su to postgres user, then run pg_dump database > outfile.

This works fine, but I'm getting tired of having to do this manually.

I'm really rusty with bash and would like to figure out a way to do the following.

1.) Write a script that will pg_dump my database to a specific directory
2.) The script should output the outfile name as hostname-date (to allow for multiple backups)
3.) Hopefully provide some form of error handling.

I've looked at the Postgres wiki and found a pretty elaborate script that does this, but was wondering if there's something quick and dirty that will get the job done.

Any hints or a point in the right direction would be greatly appreciated.

Thanks guys and gals!

Best Answer

Not taking into account any specific syntax for pg_dump:

#!/bin/bash
$TODAY=`date --iso-8601` 
$BACKDIR=/backup 

pg_dump [options] > $BACKDIR/$HOSTNAME-$TODAY

if [ "$?"-ne 0]; then echo "Help" | mail -s "Backup failed" you@example.com; exit 1; fi