将输出保存到变量中,实时查看输出

时间:2013-11-09 07:05:00

标签: bash pipe interactive

我正在尝试运行命令并将其输出保存到变量中(因此我可以稍后解析它并从输出中提取信息)。我知道如何将它保存到变量中,但我希望它能够显示输出,不仅仅是在结尾,所以我可以看到正在执行的输出。或者甚至更好,能够显示它,并使用该信息过滤/执行其他命令。

我以为我可以以某种方式将命令传递到read,但无法让它工作。

以下是我一直使用的示例代码:

#!/bin/bash

count=0
function theloop() {
        while [ $count -lt 10 ]; do
                echo "the count is $count"
                sleep 1
                let count=count+1
        done
}

output=$(theloop)

echo "the output was:"
echo "$output"

这会输出计数,但只会在最后更新,而不是每秒写一行。

有人能告诉我如何将环路传输到read或其他解决方案。即使只是将它保存到我之后可以解析的变量中也是好的,只要屏幕在生成计数时每秒更新一次。

我想我可以以某种方式将tee用于临时文件,然后阅读,但这对我来说似乎是一个不优雅的解决方案。

编辑:我应该提一下,我打算在另一个我不够智能编辑的程序的输出上使用它,所以我宁愿不改变theloop()函数的答案。

3 个答案:

答案 0 :(得分:3)

您可以teetee输出到/dev/tty,而不是output=$(theloop | tee /dev/tty) 输出到临时文件中。说

output=$(theloop)

而不是

count=0
function theloop() {
        while [ $count -lt 10 ]; do
                [ $count -eq 7 ] && { echo "the count is $count" | tee /dev/tty; } || echo "the count is $count"
                sleep 1
                let count=count+1
        done
}

output=$(theloop)

echo "the output was:"
echo "$output"

并且在显示变量时你会得到输出。


编辑:根据您的comment,如果您只想向控制台显示计数7但将所有输出保留在变量中,您可以说:

tee

请注意,tee现已在函数内移动。基本上,您echo有条件地继续while read -r line; do output+="${line}\n" [[ $line == *7* ]] && echo ${line} done < <(theloop) echo "the output was:" echo -e "${output}" 一切。

如果您无法更改功能,可以说:

{{1}}

答案 1 :(得分:1)

这不使用临时文件,而是使用临时命名管道(fifo),它不占用磁盘空间(另外,我在ramdisk上创建它,因此它甚至不会触及磁盘)。

#!/bin/bash

count=0
function theloop() {
        while [ $count -lt 10 ]; do
                echo "the count is $count"
                sleep 1
                let count=count+1
        done
}

fifo=/dev/shm/foo
rm -f $fifo
mkfifo $fifo
cat <$fifo & output=$(theloop|tee $fifo)
rm $fifo

echo "the output was:"
echo "$output"

答案 2 :(得分:1)

嗯,你已经说过了。为什么不将输出管道化为read,如下所示:

theloop | while read line; do echo $line and do something with it;done

但是,请注意,您可能在读取循环中设置变量时遇到问题,以便在循环之后可以看到它们,因为管道符号后面的部分在子shell中运行。

相关问题