Linux – Using tee and Assigning to Variable

bashlinuxpipetee

I need to see output on the screen and at the same time grep the output and send grep result to variable. I think it can be done with tee but I can't figure out how exactly. I tried

mycommand | tee myvar=$(grep -c keyword)
mycommand | tee  >(myvar=$(grep -c keyword))

but this does not work. How should it be, preferrably without writting to files?

Best Answer

You would do this:

myvar=$( mycommand | tee /dev/tty | grep -c keyword )

Use tee to pipe the output directly to your terminal, while using stdout to parse the output and save that in a variable.