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.
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
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.
精彩评论