实时打印输出并同时将其保存到变量中

Print output live and save it to a variable at the same time

我知道我可以 save the output to a variable 然后 然后 打印它:

VAR=$(command)
echo "$VAR"

但这有一些缺点:

那么,我怎样才能保存输出并在控制台上看到它呢?

从我的头顶,可以tee输出到设置为原始标准输出的附加文件描述符:

exec 3>&1
VAR=$(command | tee /dev/fd/3)

需要设置 set -o pipefail 才能在 errexit 模式下检测 command 的错误。

这也行

VAR=$(command | tee /dev/tty)