如何在打印输出的同时将命令的输出存储在变量中?

How to store the output of a command in a variable at the same time as printing the output?

说我想要 echo 一些东西并将它捕获到一个变量中,同时我在我的屏幕上看到它。

echo "hello" | tee tmp_file
var=$(< tmp_file)

所以现在我可以在我的终端中看到 hello 并将其保存到变量 $var.

但是,有什么方法可以不用临时文件来做到这一点吗? tee 似乎不是解决方案,因为它说(来自 man tee 从标准输入读取并写入标准输出和文件 ,而这里它是标准输出的两倍。

我在 Bash 4.3,如果这很重要。

将其发送到标准错误。

var="$(echo "hello" | tee /dev/stderr)"

或者将stdout复制到更高的FD并发送到那里。

$ exec 10>&1
$ var="$(echo "hello" | tee /proc/self/fd/10)"
hello
$ echo "$var"
hello

使用 tee 将其直接定向到屏幕而不是标准输出

$ var=$(echo hi | tee /dev/tty)
hi
$ echo $var
hi

管道 tee 就可以了。

这是我在 this question 中提出的方法。

var=$(echo "hello" | tee /dev/tty)

然后你可以使用$var取回存储的变量。

例如:

var=$(echo "hello" | tee /dev/tty); echo "$var world"

将输出:

hello
hello world

你可以用管道做更多的事情,比如我想在终端打印一个短语,同时告诉它里面有多少"l":

count=$(echo "hello world" | tee /dev/tty | grep -o "l" | wc -l); echo "$count"

这将打印:

hello world
3

Ignacio 答案的变体:

$ exec 9>&1                                                                                                              
$ var=$(echo "hello" | tee >(cat - >&9))   
hello                                                                              
$ echo $var
hello

详情在这里: