Getting exit status of the command when using pipes

I came across a situation where i needed the exit code of last command but before passing it through the pipe.

For example, running the following command would give the exit code 0, even if the first command failed :

root@NTRTR:/tmp# wl -i eth0 assoclist | wc -l
wl: wl driver adapter not found
0
root@NTRTR:/tmp# echo $?
0
root@NTRTR:/tmp#

Now setting the pipefail option  you can actually get the exit code. If the pipefail option is set, the exit code will be zero only if all the commands in the pipeline exit successfully. The option is disabled by default and can be enabled by using theset command:  set -o

set -o pipefail

Now let's check the output after setting the pipefail option:

root@NTRTR:/tmp# set -o pipefail
root@NTRTR:/tmp# wl -i eth0 assoclist | wc -l
wl: wl driver adapter not found
0
root@NTRTR:/tmp# echo $?
1
root@NTRTR:/tmp#

In order to reset :

set +o pipefail

Reference:

The Set Builtin (Bash Reference Manual)
The Set Builtin (Bash Reference Manual)