Take the 2-minute tour ×

i currently wonder how to do error handling for chained commands. the following is just an example to easy demonstrate my problem:

cat file | gzip >/tmp/test

if cat fails (because for example file is missing), gzip is still executed and therefore the last stored exit code in $? is 0. set -e won't help either in this case.

i wonder what's the best solution for this?


share|improve this question
Have you tried $PIPESTATUS ? It should work for bash. –  khachik Dec 17 '10 at 16:11
i did not even know, that this existed. thanks! –  aurora Dec 20 '10 at 9:07
add comment

1 Answer

up vote 6 down vote accepted

Try this:

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

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

share|improve this answer
wow -- that's very cool. i did not know of this possibility. thanks very much! –  aurora Dec 20 '10 at 9:07
add comment

Your Answer


