在 Bash 中捕获 stdout 和 stderr [英] Capture both stdout and stderr in Bash

查看:37
本文介绍了在 Bash 中捕获 stdout 和 stderr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个语法

var=`myscript.sh`

var=$(myscript.sh)

myscript.sh的结果(stdout)捕获到var中.如果我想同时捕获两者,我可以将 stderr 重定向到 stdout.如何将它们中的每一个保存到单独的变量中?

Will capture the result (stdout) of myscript.sh into var. I could redirect stderr into stdout if I wanted to capture both. How to save each of them to separate variables?

我的用例是,如果返回码非零,我想回显 stderr 否则抑制.可能还有其他方法可以做到这一点,但如果确实可行,这种方法似乎会奏效.

My use case here is if the return code is nonzero I want to echo stderr and suppress otherwise. There may be other ways to do this but this approach seems it will work, if it's actually possible.

推荐答案

没有临时文件,无法同时捕获两者.

There is no way to capture both without temp file.

您可以将 stderr 捕获到变量并将 stdout 传递到用户屏幕(示例来自 此处):

You can capture stderr to variable and pass stdout to user screen (sample from here):

exec 3>&1                    # Save the place that stdout (1) points to.
output=$(command 2>&1 1>&3)  # Run command.  stderr is captured.
exec 3>&-                    # Close FD #3.

# Or this alternative, which captures stderr, letting stdout through:
{ output=$(command 2>&1 1>&3-) ;} 3>&1

但是没有办法同时捕获标准输出和标准错误:

But there is no way to capture both stdout and stderr:

你不能做的是在一个变量中捕获 stdout,在另一个变量中捕获 stderr,只使用 FD 重定向.您必须使用临时文件(或命名管道)来实现这一目标.

What you cannot do is capture stdout in one variable, and stderr in another, using only FD redirections. You must use a temporary file (or a named pipe) to achieve that one.

这篇关于在 Bash 中捕获 stdout 和 stderr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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