Saturday, August 27, 2011

capture exit codes of piped commands

In bash, if you run a command like this:

$ foo | bar


The exit codes of all the piped commands get stored into a special bash array ${PIPESTATUS. Specifically, the exit code of foo is in ${PIPESTATUS[0]}, and bar is in ${PIPESTATUS[1]}.

Here is it where it gets tricky - PIPESTATUS is volatile. If you check one array location, the variable gets overwritten. So, if you want to check more than one of the exit codes you need to store the array into another array, like this:


$ foo | bar
$ STORED_PIPESTATUS=("${PIPESTATUS[@]}")

No comments:

Post a Comment