How to get status codes from commands in pipe


A pipe is a form of redirection io-streams. It helps transfer standard output to some other destination. That is used in Linux and other Unix-like operating systems to send the output of one to another.

One by one Unix programs can modify output. But what if one of them fails?

The members of the $PIPESTATUS array hold the exit status of each respective command executed in a pipe.

So you can see all statuses of the pipe using ${PIPESTATUS[@]}

For example:

$ echo foo | grep bar | tr z a | cat | false | true
$ echo ${PIPESTATUS[@]} 
0 1 0 0 1 0

Now you know which element of pipe-chain failed.