MathematicalOrchid
MathematicalOrchid

Reputation: 62818

Monitor pipeline exit codes

I have a Bash script which spawns a gigantic shell pipeline as a background process, and then spawns various other processes that communicate with it through named pipes. (Sounds complicated? Well, it is!) It looks something like this:

generate_stuff | tee >(process1) >(process2) | process3 | save_stuff &

The script works just fine, however... it doesn't handle errors properly. There are various error conditions which can cause one or more of the commands in the pipeline to fail. Currently the script blindly reports that everything went fine, when in fact only some of the commands completed successfullly.

Is there some way I can check whether all commands ended with exit code zero? Hopefully without making this giant script any more complex than it already is...?

Upvotes: 2

Views: 141

Answers (2)

Zaphod B
Zaphod B

Reputation: 36

You may be looking for set -e and set -o pipefail.

From Bash manual:

pipefail     If set, the return value of a pipeline is the value of the last (rightmost) command to exit with a non-zero status, or zero if all commands in the pipeline exit successfully. This option is disabled by default.

Upvotes: 2

damienfrancois
damienfrancois

Reputation: 59130

You an use $PIPESTATUS : "Array variable holding exit status(es) of last executed foreground pipe." See more details here.

$ echo ok | tee | grep ko | cat
$ echo ${PIPESTATUS[@]}
0 0 1 0

For a background pipe, you can try

$ ( echo ok | tee | grep ko | cat ; echo ${PIPESTATUS[@]} ) &
[1] 16660
0 0 1 0
[1]+  Done                    ( echo ok | tee | grep ko | cat; echo ${PIPESTATUS[@]} )

Upvotes: 3

Related Questions