Whenever the output of a command is piped to another in bash, which command will the exit value (the $? variable) be returned from? The command that the output was piped from, or the command that the output was piped to?

Say, for example, in the command:

git diff | vim -

Would the $? variable come from the git diff command, or the vim - command?

link|improve this question

feedback

3 Answers

up vote 5 down vote accepted

The last command in the pipe.

$ false | echo -n
$ echo $?
0

$ true | echo -n
$ echo $?
0

$ true | echo -n | false
$ echo $?
1
link|improve this answer
feedback

man bash says:

   ?      Expands to the exit status of the most recently  executed  fore‐
          ground pipeline.

And:

   The return status of a pipeline is the exit status of the last command,
   unless the pipefail option is enabled.
link|improve this answer
feedback

The $? keeps the status of the last executed command in a pipeline, but if you want to check the status of a command inside the pipeline use the PIPESTATUS variable, which is

An array variable (see Arrays) containing a list of exit status values from the processes in the most-recently-executed foreground pipeline (which may contain only a single command).

In your example the return status of git diff can be read from ${PIPESTATUS[0]}.

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.