tags:

views:

40

answers:

2

Hi, I have a bash script that watch's a directory for uploads. When it sees a xml file in the directory. The script takes the file and calls a java command line program that using xslt transforms the file. I want to mv the file to a different directory (errors) if the script or java command line program throws a error during processing. Then email me the error.

I was going to put exec 2> mail -s 'Statement Error Processing'

at the top of the script to catch output for stderr. But that doesn't seem very elegant and doesn't move the file in question.

+2  A: 

You can trap error conditions in bash (any statement that returns a non-zero condition that isn't handled inline):

trap func ERR

Then in func (a function you define) you can do whatever you need to clean up.

For example:

#!/bin/bash

function foo() {
    echo "cleaning up"
}

trap foo ERR

echo "about to execute false"

false

echo "exiting"

Running that will result in:

./foo.sh
about to execute false
cleaning up
exiting
kanaka
An `ERR` trap or `set -e` don't really seem beneficial if there is only one command to check ;-)
jilles
+3  A: 

You need two things here. First, determine if the program fails. This is usually known by the return value of the program's main() function. If the program returns anything different to 0, there is an error.

In any case, the second thing you have to do is to capture the standard error output to a file to later mail it. So:

if ! program inputfile 2> errorfile ; then
    mv inputfile error_directory
    mail -s "error" < errorfile
fi
rm errorfile

You have to check, though, if your program follows this convention to signal an error.

Diego Sevilla
`test` should not be literal here. The program should be invoked directly after the `!` keyword, the `test` builtin utility is not involved.
jilles
Oops. You're right. Corrected. Thanks!
Diego Sevilla