Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
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

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

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .