导航:[首页]->[bash]->[Shell管道失败后立即返回]
    #!/bin/sh
    # XXX命令不存在
    XXX | sed s/a/b/g 

以上命令在我机器(以及测试的若干其他机器)会返回成功,但实际上XXX并不存在,按道理应该返回失败的。

bash手册

Each command in a pipeline is executed in its own subshell . The exit status of a pipeline is the exit status of the last command in the pipeline, unless the pipefail option is enabled .

pipefail

If set, the return value of a pipeline is the value of the last (rightmost) command to exit with a non-zero status, or zero if all commands in the pipeline exit successfully. This option is disabled by default.

    #!/bin/sh
    # XXX命令不存在
    set -o pipefail
    XXX | sed s/a/b/g 

PIPESTATUS

你也可以使用PIPESTATUS变量访问管道中各个脚本的返回值

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

http://www.gnu.org/software/bash/manual/bashref.html#Bourne-Shell-Variables