fedorqui
fedorqui

Reputation: 290515

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

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.

Upvotes: 36

Views: 22125

Answers (4)

MatrixManAtYrService
MatrixManAtYrService

Reputation: 9231

A variation on Ignacio's answer:

$ exec 9>&1                                                                                                              
$ var=$(echo "hello" | tee >(cat - >&9))   
hello                                                                              
$ echo $var
hello

Details here: https://stackoverflow.com/a/12451419/1054322

Upvotes: 6

Leo
Leo

Reputation: 13858

Pipe tee does the trick.

This is my approach addressed in this question.

var=$(echo "hello" | tee /dev/tty)

Then you can use $var to get back the stored variable.

For example:

var=$(echo "hello" | tee /dev/tty); echo "$var world"

Will output:

hello
hello world

You can do more with pipes, for example I want to print a phrase in the terminal, and at the same time tell how many "l"s are there in it:

count=$(echo "hello world" | tee /dev/tty | grep -o "l" | wc -l); echo "$count"

This will print:

hello world
3

Upvotes: 11

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799520

Send it to stderr.

var="$(echo "hello" | tee /dev/stderr)"

Or copy stdout to a higher FD and send it there.

$ exec 10>&1
$ var="$(echo "hello" | tee /proc/self/fd/10)"
hello
$ echo "$var"
hello

Upvotes: 5

123
123

Reputation: 11246

Use tee to direct it straight to screen instead of stdout

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

Upvotes: 49

Related Questions