1

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?

5

The last command in the pipe.

$ false | echo -n
$ echo $?
0

$ true | echo -n
$ echo $?
0

$ true | echo -n | false
$ echo $?
1
5

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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