Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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?

share|improve this question
add comment

3 Answers 3

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
share|improve this answer
add comment

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.
share|improve this answer
add comment

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]}.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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