How to store the output of a command in a variable at the same time as printing the output?

fedorqui 'SO stop harming' picture fedorqui 'SO stop harming' · May 6, 2016 · Viewed 12.7k times · Source

Say I want to echo something and capture it in a variable, at the same time I see it in my screen.

echo "hello" | tee tmp_file
var=$(< tmp_file)

So now I could see hello in my terminal as well as saving it into the variable $var.

However, is there any way to do this without having to use a temporary file? tee doesn't seem to be the solution, since it says (from man tee) read from standard input and write to standard output and files, whereas here it is two times standard output.

I am in Bash 4.3, if this matters.

Answer

123 picture 123 · May 6, 2016

Use tee to direct it straight to screen instead of stdout

$ var=$(echo hi | tee /dev/tty)
hi
$ echo $var
hi