同时捕获stdout和stderr在bash [英] capture both stdout and stderr in bash

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

问题描述

我知道这个语法

var=`myscript.sh`

var=$(myscript.sh)

将捕获 myscript.sh 的结果(标准输出)到 VAR 。我能标准错误重定向到标准输出如果我想同时捕获。如何保存他们每个人给独立的变量?

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?

我在这里的使用情况是如果返回code是非零我想呼应,否则标准错误和SUP preSS。可能有其他的方法可以做到这一点,但这种做法似乎会工作,如果它实际上是可能的。

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.

您可以捕捉标准错误变量,并通过(从这里样品)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:

什么你不能做的是捕获标准输出一个变量和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.

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

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