Bash 中的管道输出和捕获退出状态 [英] Pipe output and capture exit status in Bash
问题描述
我想在 Bash 中执行一个长时间运行的命令,并捕获它的退出状态,以及 tee 它的输出.
I want to execute a long running command in Bash, and both capture its exit status, and tee its output.
所以我这样做:
command | tee out.txt
ST=$?
问题在于变量 ST 捕获了 tee
的退出状态,而不是命令的退出状态.我该如何解决这个问题?
The problem is that the variable ST captures the exit status of tee
and not of command. How can I solve this?
请注意,该命令长时间运行并将输出重定向到文件以供稍后查看对我来说不是一个好的解决方案.
Note that command is long running and redirecting the output to a file to view it later is not a good solution for me.
推荐答案
有一个内部的 Bash 变量叫做 $PIPESTATUS
;它是一个数组,用于保存最后一个前台命令管道中每个命令的退出状态.
There is an internal Bash variable called $PIPESTATUS
; it’s an array that holds the exit status of each command in your last foreground pipeline of commands.
<command> | tee out.txt ; test ${PIPESTATUS[0]} -eq 0
或者另一种也适用于其他 shell(如 zsh)的替代方法是启用 pipefail:
Or another alternative which also works with other shells (like zsh) would be to enable pipefail:
set -o pipefail
...
由于语法稍有不同,第一个选项不能与 zsh
一起使用.
The first option does not work with zsh
due to a little bit different syntax.
这篇关于Bash 中的管道输出和捕获退出状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!