Kan Li
Kan Li

Reputation: 8797

Bash: how to detect error in pipe

I have commands like this:

COMMAND1 &&
COMMAND2 | COMMAND3 | COMMAND4 &&
COMMAND5

I want to make sure all of the COMMAND 1-5 are successful. Is there an easy way to achieve this? By doing research, I found PIPESTATUS can be used, but yield to some very complicated commands like

COMMAND1 &&
COMMAND2 | COMMAND3 | COMMAND4 &&
($PST=("${PIPESTATUS[@]}") && (exit ${PST[0]}) && (exit ${PST[1]})) &&
COMMAND5

Is there a way to do it easily?

BTW: I used (exit n) to get a command that does nothing but exit with status n. Is there a UNIX command that does this directly, like true and false?

Thanks.

Upvotes: 3

Views: 707

Answers (1)

Foo Bah
Foo Bah

Reputation: 26271

Try using set -o pipefail. This ensures that the error code of the pipeline is the error code of the last process with an error.

Upvotes: 9

Related Questions