0

Let's say I execute the following command on a terminal:

this-command-doesnt-exist-and-closes-with-code-127 | jq '' 

If I execute echo $? I'll get 0 as result because it's checking the exit code from jq. I'd like to know the exit code from the first command on the pipe. I thought about redirecting the stderr like:

this-command-doesnt-exist-and-closes-with-1 2>&1 | jq '' if [ $? != 0 ]; then echo "I got an error" fi 

Just so I send a message that doesn't make sense to jq. It'd solve the problem but it doesn't look like the right solution for it. How can I manage getting the error code of commands on pipes?

1 Answer 1

4

If you are using bash you can use set -o pipefail:

$ set -o pipefail $ this-command-doesnt-exist-and-closes-with-code-127 | jq '' bash: this-command-doesnt-exist-and-closes-with-code-127: command not found... $ echo $? 127 

From bash man page:

pipefail

If set, the return value of a pipeline is the value of the last (rightmost) command to exit with a non-zero status, or zero if all commands in the pipeline exit successfully. This option is disabled by default.

1
  • 2
    +1. There's also the PIPESTATUS array in bash, which contains the list of exit status values from commands in the most-recently-executed pipeline. There are several questions and answers on this site about it. Commented May 5, 2022 at 3:55

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.