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.
To store the output of a command in a variable, you can use the shell command substitution feature in the forms below: variable_name=$(command) variable_name=$(command [option ...] arg1 arg2 ...) OR variable_name='command' variable_name='command [option ...]
The tee command, used with a pipe, reads standard input, then writes the output of a program to standard output and simultaneously copies it into the specified file or files. Use the tee command to view your output immediately and at the same time, store it for future use.
Use tee to direct it straight to screen instead of stdout
$ var=$(echo hi | tee /dev/tty) hi $ echo $var hi
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With