Redirecting output that was redirected to variable and console

Hi all,

I would like to store the output of a command in a variable and output it to the console at the same time. This is working fine using the following construct

var=`command | tee /dev/tty`

I use this in some scripts to display the output of the command on the console and, at the same time check the output for certain flags, which indicate successful/failed execution (This may not be good practise and would better be done using the return code of the command, but I have no control over the command and some errors can only be detected by checking for certain output).

The problem is that the ouput of the above command can no longer be redirected. As an example:

var=`echo test | tee /dev/tty` > /dev/null

will still output test.

Is there a better way to do this? Of course there are alternatives:

  • I could only store the output in the variable and not write it to the console simulteaniously. Once the command has completed the variable could be printed to the console. Though, I think it's nice to get a live view of what's going on.
  • Also, I'm aware that I could just tee the output to the console and a file and subsequently grep for the flags in the file. Though, I'd like to avoid creating a file.

So, is it possible to redirect the ouput of a command to the console and to a variable in a way, that you could also redirect the output that goes to the console at a later point in time?

Thanks for your help
Ben

A possible technique :

if display required
then
   Console=/dev/tty
else
   Console=/dev/null
fi

var=$(command | tee $Console)

Jean-Pierre.

Thanks for the reply.

Please note that the output should be redirectable to a file. The example redirecting to /dev/null

var=`echo test | tee /dev/tty` > /dev/null

was only to illustrate the problem.