Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
292 views
in Technique[技术] by (71.8m points)

command - In Bash, how to set stdout to a variable inside 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)

Output:

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

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 

Expected Output

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

But what I got is an Unexpected Missing Output for myVar

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

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

question from:https://stackoverflow.com/questions/66047064/in-bash-how-to-set-stdout-to-a-variable-inside-tee

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
#!/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 

Result:

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

Try it online!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...