开发者

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

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 fi开发者_开发技巧le 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?

thanks!


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜