bashplatform-agnostic

Print output live and save it to a variable at the same time


I know that I can save the output to a variable and then print it:

VAR=$(command)
echo "$VAR"

But this has a number of drawbacks:

So, how can I save the output and also see it live on the console?


Solution

  • From the top of my head, one can tee the output to an additional file descriptor set to the original stdout:

    exec 3>&1
    VAR=$(command | tee /dev/fd/3)
    

    One needs to have set -o pipefail set to detect command's error in errexit mode.