加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

在Bash中捕获stdout和stderr

发布时间:2020-12-16 01:40:17 所属栏目:安全 来源:网络整理
导读:参见英文答案 Capture stdout and stderr into different variables????????????????????????????????????13个 我知道这个语法 var=`myscript.sh` 要么 var=$(myscript.sh) 将myscript.sh的结果(stdout)捕获到var中.如果我想捕获两者,我可以将stderr重定向到
参见英文答案 > Capture stdout and stderr into different variables????????????????????????????????????13个
我知道这个语法

var=`myscript.sh`

要么

var=$(myscript.sh)

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

我的用例是如果返回代码非零,我想回显stderr并禁止其他方式.可能有其他方法可以做到这一点,但这种方法似乎可行,如果它实际上是可能的.

解决方法

没有临时文件就无法捕获它们.

您可以将stderr捕获到变量并将stdout传递给用户屏幕(样本来自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

但是没有办法捕获stdout和stderr:

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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读