在 Bash 中,如何将 stdout 设置为 tee 内的变量

In Bash, how to set stdout to a variable inside tee

使用 Bash,我想检查终端上的输出,但同时将该输出提供给另一个命令以进行进一步处理。这里我使用tee

#!/bin/bash

function printToStdout() {
  echo "Hello World is printed to stdout"
  echo "This is the second line"
}
printToStdout | tee >(grep Hello)

输出:

Hello World is printed to stdout
This is the second line
Hello World is printed to stdout

到目前为止一切顺利。但我需要将 grep 结果传递给 1 个以上的自定义函数以进行进一步处理。因此,我尝试通过在 tee:

中使用命令替换将其存储到变量中
printToStdout | tee >(myVar=`grep Hello`)
echo "myVar: " $myVar 

预期输出

Hello World is printed to stdout
This is the second line
myVar: Hello World is printed to stdout

但我得到的是 myVar

的意外缺失输出
Hello World is printed to stdout
This is the second line
myVar: 

问题: 如何将 grep 的输出放入 myVar 以便我可以进一步处理它?

#!/bin/bash

function printToStdout() {
  echo "Hello World is printed to stdout"
  echo "This is the second line"
}

{ myVar=$(printToStdout | tee >(grep Hello) >&3); } 3>&1

echo "myVar: " $myVar 

结果:

Hello World is printed to stdout
This is the second line
myVar:  Hello World is printed to stdout

Try it online!