How to store the output of a command in a variable

2019-02-23 07:35发布

问题:

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.

回答1:

Use tee to direct it straight to screen instead of stdout

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


回答2:

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


回答3:

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


回答4:

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



标签: bash stdout gnu