On Mon, 2 Jan 2006, alexandre - aldeia digital wrote:
In my Linux bash backup scripts, I wish to send an e-mail when an error
occurs in pg_dump proccess. And if possible, I want to send the error output
via e-mail.
Anybody knows how to capture the output and send this to an e-mail ONLY if an
error occurs ?
I wrote a generic bash shell script to handle this kind of thing in cron.
See the attachment. As long as the program you're running returns an exit
value of 0 when it succeeds, and a non-zero value when it fails, this will
work. (Thought it's not documented in pg_dump's man page, it does return
sane exit values.)
Just do something like:
/path/to/cron-harness pg_dump your-arguments-here
If pg_dump succeeds, nothing will be output. If it fails, all the normal
output will be returned (and if this is a cron job, mailed to you, by
default).
Check the arguments to mktemp, which may vary on your platform. Any
suggestions or improvements are welcome!
HTH,
Jon
--
Jon Jensen
End Point Corporation
http://www.endpoint.com/
Software development with Interchange, Perl, PostgreSQL, Apache, Linux, ...
#!/bin/bash
# cron-harness
# by Jon Jensen <jon@xxxxxxxxxxxx>
# $Id: cron-harness,v 1.3 2005/12/31 15:28:25 jon Exp $
#
# Invocation:
# cron-harness [ -e email@address ] some-program and its args
#
# Run some program. If it returns an error exit value, either email its
# output somewhere (if the -e option is given) or simply send it to stdout
# (the default); otherwise be silent.
email=
while getopts e: opts
do
if [ "$opts" = e ]; then
email=$OPTARG
elif [ "$opts" = '?' ]; then
echo "cron-harness: Error parsing options" >&2
exit 1
fi
done
shift $(($OPTIND - 1))
if [ -z "$*" ]; then
echo "cron-harness: No command given" >&2
exit 1
fi
outfile=`mktemp -t cron-harness.out.XXXXXXXXXX`
if [ $? -ne 0 ]; then
echo "cron-harness: Error creating temporary file" >&2
exit 1
fi
exit=0
$* > $outfile 2>&1
if [ $? -ne 0 ]; then
if [ -n "$email" ]; then
hostname=`hostname | sed 's/\..*//'`
mail -s "cron-harness: Error running $1 on $hostname" $email < $outfile
else
cat $outfile
fi
exit=2
fi
rm -f $outfile
exit $exit