庆典:捕获标准输出到一个变量,但仍然在控制台中显示它 [英] bash: Capture stdout to a variable but still display it in the console

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

问题描述

我有一个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 /标准错误。我觉得输出到/ dev /标准错误不是一个做事的好方法。

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),并用和5中的子shell(这样你会写入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.

在您的code:

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

这篇关于庆典:捕获标准输出到一个变量,但仍然在控制台中显示它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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