Search code examples
bashstdoutio-redirectiontee

Print command output while storing in variable


I am running unit tests in a bash shell, which can take some time to finish, and those tests print output as they run. I want this output to be printed, and I also want the output to be stored in a variable. However, I want these things to be done concurrently if possible, like the tee command does when writing to a file. Perhaps tee works in this case too…

So I am currently doing this:

output=$(ginkgo -r -cover)
echo "$output"

However, this obviously won't print the unit test output until all the tests have run. So how can I get the output to print as the tests run while also storing that output in a variable?


Solution

  • output=$(ginkgo -r -cover | tee /dev/fd/2)
    

    You can use tee to send stdout to both stdout and stderr. stdout is captured into your variable, stderr is printed.