T.L T.L - 1 month ago 8
Bash Question

Print command result while executing from script

I am trying to run from a shell script a C++ program that print some outputs (using

std::cout
), and I would like to see them in the console while the program is running.

I tried some things like this :

RES=`./program`
RES=$(./program)


But all I can do is to only display the result at the end :
echo $RES
...

How to display the outputs in run-time in the console, AND in the variable
RES
?

Answer
TTY=$(tty);
SAVED_OUTPUT=$(echo "my dummy c++ program" | tee ${TTY});
echo ${SAVED_OUTPUT};

prints

my dummy c++ program
my dummy c++ program

First we save off the name of the current terminal (because tty doesn't work in a pipeline).

TTY=$(tty)

Then we "T" the output (a letter T looks like one stream in at the bottom, 2 out at the top, and comes from the same "plumbing" metaphor as "pipe"), which copies it to the filename given; in this case the "file" is really a special device representing our terminal.

echo "my dummy c++ program" | tee ${TTY}