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

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

问题描述

我有一个 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(&5)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 两次,一次是因为子shell中的回声,第二次打印变量的值.

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

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

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