System Administration Toolkit: Build intelligent, unattended scripts
Look at how to create scripts that are able to record their output, trap and identify errors, and recover from errors and problems so that they either run correctly or fail with a suitable error message and report.