我想在Bash中执行一个长时间运行的命令,并捕获它的退出状态,并输出它的输出。

所以我这样做:

command | tee out.txt
ST=$?

问题是变量ST捕获tee的退出状态,而不是命令的退出状态。我怎么解决这个问题?

注意,该命令长时间运行,将输出重定向到文件以供以后查看,这对我来说不是一个好的解决方案。


当前回答

愚蠢的解决方案:通过命名管道(mkfifo)连接它们。然后可以再次执行该命令。

 mkfifo pipe
 tee out.txt < pipe &
 command > pipe
 echo $?

其他回答

这个解决方案不需要使用bash特定的特性或临时文件。好处:最后,退出状态实际上是一个退出状态,而不是文件中的某个字符串。

情境:

someprog | filter

您需要someprog的退出状态和filter的输出。

以下是我的解决方案:

((((someprog; echo $? >&3) | filter >&4) 3>&1) | (read xs; exit $xs)) 4>&1

echo $?

请参阅我在unix.stackexchange.com上对同一问题的回答,以获得详细的解释和没有子shell和一些注意事项的替代方案。

愚蠢的解决方案:通过命名管道(mkfifo)连接它们。然后可以再次执行该命令。

 mkfifo pipe
 tee out.txt < pipe &
 command > pipe
 echo $?

PIPESTATUS[@]必须在管道命令返回后立即复制到一个数组中。 任何对PIPESTATUS[@]的读取都将删除该内容。 如果计划检查所有管道命令的状态,则将其复制到另一个数组。 $?与${PIPESTATUS[@]}的最后一个元素值相同, 读它似乎破坏了“${PIPESTATUS[@]}”,但我还没有完全验证这一点。

declare -a PSA  
cmd1 | cmd2 | cmd3  
PSA=( "${PIPESTATUS[@]}" )

如果管道位于子外壳中,这将不起作用。为了解决这个问题, 查看bash pipestatus在backtick命令?

有一个内部Bash变量叫做$PIPESTATUS;它是一个数组,保存最后一个前台命令管道中每个命令的退出状态。

<command> | tee out.txt ; test ${PIPESTATUS[0]} -eq 0

或者另一种也适用于其他shell(如zsh)的选择是启用pipefail:

set -o pipefail
...

由于语法略有不同,第一个选项不能用于zsh。

有一个数组为您提供管道中每个命令的退出状态。

$ cat x| sed 's///'
cat: x: No such file or directory
$ echo $?
0
$ cat x| sed 's///'
cat: x: No such file or directory
$ echo ${PIPESTATUS[*]}
1 0
$ touch x
$ cat x| sed 's'
sed: 1: "s": substitute pattern can not be delimited by newline or backslash
$ echo ${PIPESTATUS[*]}
0 1