Sep 16, 2010

BASH: pipe command output and track the error codes

Anar here...

I've just came across a problem in on of the projects I work on.
I have a bunch of commands in a "pipe line"... something like the following.

command 2>&1 | command2 | command3

Now, what I want is to check the exit code of the first command. If I would use the "$?" than it will return the exit code of the last command, which is not what I need.

The solution is to use bash's PIPESTATUS, which will return an array of exit codes of each command in a line ;)
See what man bash says:
An array variable (see Arrays below) containing a list of exit status values from the processes in the most-recently-executed foreground pipeline (which may contain
only a single command).
So, if I apply the solution to my example above I get something like that:

command 2>&1 | command2 | command3

if (( ${PIPESTATUS[0]} != 0 )); then
echo "something is wrong..."
"In UNIX there is always a workaround" ;)

No comments: