管道输出并捕获Bash中的退出状态 [英] Pipe output and capture exit status in Bash

查看:84
本文介绍了管道输出并捕获Bash中的退出状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Bash中执行长时间运行的命令,并且都捕获其退出状态,并且其输出.

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.

推荐答案

内部有一个名为$PIPESTATUS的Bash变量.它是一个数组,用于保存最后一个命令前台管道中每个命令的退出状态.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆