本文介绍了在Bash中,如何将stdout设置为tee内的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

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

Using Bash, I want to inspect the output on the terminal but at the same time feed that output to another command for further processing. Here I use 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 结果传递到多个自定义函数中以进行进一步处理.因此,我尝试通过在 tee 内使用命令替换将其存储到变量中:

So far so good. But I need the grep result to pass into more than 1 custom function for further processing. Hence, I try to store that to a variable by using command substitution inside 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中,以便我可以对其进行进一步处理?

Question: how can I get the output of grep into myVar so that I can further process it?

推荐答案

#!/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

尝试在线!

这篇关于在Bash中,如何将stdout设置为tee内的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-08 05:41