re: How to Automate Dumping for SQL Databases VIEW POST


have you thought about what happens when pg_dump fails for some reason?

you would then have an empty dump.sql which is copied to the remote server and overwrites your backup.


That's true, but doesn't it depend on how exactly it fails, the dump file might not necessarily be replaced if it had network connectivity issues. But I see your point, I think there should be an if block that handles errors and sends the content to a mailbox or something.


as far as i know at least bash always creates the output file


it actually does, just tried it. How will you have handled it?

i would just use the same if [ $? -eq 0 ]; thing.

maybe also add the date to the file name to prevent it from being overwritten on the remote server

That should work or we just move the scp command

pg_dump bla bla bla > dump.sql

if [$? -eq 0]; 
   scp -i "" ...
   echo "backup successful" && rm dump.sql
   cat dump.sql | mailx 'youremailaddress' -s "backup failure"
   echo "backup failure" && rm dump.sql

I would do it like this:

pg_dump... > dump.sql

if [$? -ne 0];
    exit 1

scp... && rm dump.sql

usually all the output from a cronjob is sent to you via email so no need for mailx etc.
When pg_dump encounters an error it also should write it to stderr so it won't end up in your dump file. Instead it will be printed to your screen when you run the script manually or get sent to you via mail when it is started as a cronjob

Even shorter solution:


set -o errexit

pg_dump... > dump.sql

set -o errexit will cause the script to end as soon as any command fails.

code of conduct - report abuse