Error handling with chained commands (pipes) in a bash script?

I'm currently wondering how to do error handling for chained commands. The following is just an example to easily demonstrate my problem:

cat file | gzip >/tmp/test 

If the cat fails (because, for example, the file is missing), gzip is still executing and therefore the last stored exit code in $? is 0. set -e will not help in this case.

I wonder what is the best solution for this?

thanks!

+6
bash error-handling
source share
1 answer

Try the following:

 trap 'echo "ERR caught"' ERR set -o pipefail cat file | gzip >/tmp/test 

The output file will still be created (creation is done in parallel) and gzip will be launched, but you can do the cleanup. Use the ${PIPESTATUS[@]} array to see where the error occurred. You can use $BASH_COMMAND and $BASH_LINENO for more error information.

+8
source share

All Articles