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

826 views Asked by At

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:

  • I won't see the progress of the command as it goes.
    • In particular, will see all stdout output after all stderr output, making it hard to match them.
  • Since this will result in no output for the duration of the command's work, in some environments (like Travis CI) this will terminate the job if the command works for long enough.

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

  • Portable solutions are preferrable though a Linux/MacOS-only one will do in a pinch.
  • A solution should not have undesirable side effects in errexit mode
2

There are 2 answers

0
ivan_pozdeev On BEST ANSWER

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.

4
Cupid Chan On

This will also work

VAR=$(command | tee /dev/tty)