Exit value with piped commands in bash

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?

Wuffers

Posted 2011-05-08T22:46:46.400

Reputation: 16 645

Answers

5

The last command in the pipe.

$ false | echo -n
$ echo $?
0

$ true | echo -n
$ echo $?
0

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

Majenko

Posted 2011-05-08T22:46:46.400

Reputation: 29 007

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.

Michaël Witrant

Posted 2011-05-08T22:46:46.400

Reputation: 252

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

Rajish

Posted 2011-05-08T22:46:46.400

Reputation: 570