在 bash 中使用管道命令退出值

Wuf*_*ers 2 bash

每当命令的输出通过管道传送到 bash 中的另一个命令时,退出值($?变量)将从哪个命令返回?输出通过管道传输的命令,还是输出通过管道传输到的命令?

例如,在命令中说:

git diff | vim -
Run Code Online (Sandbox Code Playgroud)

请问$?变量来自于git diff命令或vim -指令?

Maj*_*nko 6

管道中的最后一个命令。

$ false | echo -n
$ echo $?
0

$ true | echo -n
$ echo $?
0

$ true | echo -n | false
$ echo $?
1
Run Code Online (Sandbox Code Playgroud)


Mic*_*ant 6

man bash 说:

   ?      Expands to the exit status of the most recently  executed  fore?
          ground pipeline.
Run Code Online (Sandbox Code Playgroud)

和:

   The return status of a pipeline is the exit status of the last command,
   unless the pipefail option is enabled.
Run Code Online (Sandbox Code Playgroud)