将stdout捕获到变量,但仍将其显示在控制台中 [英] Capture stdout to a variable but still display it in the console

查看:122
本文介绍了将stdout捕获到变量,但仍将其显示在控制台中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个bash脚本,它调用了几个长时间运行的进程.由于处理原因,我想将这些调用的输出捕获到变量中.但是,由于这些进程是长期运行的进程,因此我希望rsync调用的输出在实时中而不是在事后显示在控制台中.

I have a bash script which calls several long-running processes. I want to capture the output of those calls into variables for processing reasons. However, because these are long running processes, I would like the output of the rsync calls to be displayed in the console in real-time and not after the fact.

为此,我找到了 的一种实现方法,但它依赖于输出文本到/dev/stderr.我觉得输出到/dev/stderr并不是一个好方法.

To this end, I have found a way of doing it but it relies on outputting the text to /dev/stderr. I feel that outputting to /dev/stderr is not a good way of doing things.

VAR1=$(for i in {1..5}; do sleep 1; echo $i; done | tee /dev/stderr)

VAR2=$(rsync -r -t --out-format='%n%L' --delete -s /path/source1/ /path/target1 | tee /dev/stderr)

VAR3=$(rsync -r -t --out-format='%n%L' --delete -s /path/source2/ /path/target2 | tee /dev/stderr)

在上面的示例中,我多次调用rsync,并希望在处理文件时看到它们的名称,但是最后我仍然希望将输出结果包含在变量中,因为稍后将对其进行解析.

In the example above, I am calling rsync a few times and I want to see the file names as they are processed, but in the end I still want the output in a variable because I will be parsing it later.

是否有一种更清洁"的方法来实现这一目标?

Is there a 'cleaner' way of accomplishing this?

如果有所作为,我正在使用Ubuntu 12.04,bash 4.2.24.

If it makes a difference, I am using Ubuntu 12.04, bash 4.2.24.

推荐答案

在您的shell中复制& 1(在我的示例中为5),在子shell中使用& 5(以便您将写入stdout(& 1)的父外壳):

Duplicate &1 in your shell (in my examle to 5) and use &5 in the subshell (so that you will write to stdout (&1) of the parent shell):

exec 5>&1
FF=$(echo aaa|tee >(cat - >&5))
echo $FF

将两次打印aaa,一次是由于子外壳中的回显,而第二次将打印变量的值.

Will print aaa two times, ones because of the echo in the subshell, and second time print the value of the variable.

在您的代码中:

exec 5>&1
VAR1=$(for i in {1..5}; do sleep 1; echo $i; done | tee >(cat - >&5))
# use the value of VAR1

这篇关于将stdout捕获到变量,但仍将其显示在控制台中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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