My question is similar to Get exit status of process that's piped to another, but I want to get the exit status of the second command in the pipe within the pipe.
Here's an example -
false | echo $?
returns 0
rather than the intended 1
PIPESTATUS
gives the previous error code out
false | echo $PIPESTATUS
returns 0
the first time and then 1
, giving the result after the operation itself. My intent with this is to make a function like this:
debug() {
# Eventually will be formatted as JSON
echo "$(cat) was the result and the error code was $?"
}
(
echo "Foo"
false # To simulate an error
) | debug # debug should return "Foo was the result and the error code was 1"
whatever; printf ' was the result and the error code was %d\n' "$?"
. But if they want to reformat the output as JSON or something, they'll have to buffer. A minor point to note is that command substitution eats trailing newlines, so if you want to avoid that, just using a temporary file might be a thing to consider. – ilkkachu Apr 25 '23 at 07:47