Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 773
fedorqui 'SO stop harming' Avatar asked May 06 '16 08:05

fedorqui 'SO stop harming'


People also ask

How do you store command output in a variable?

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 ...]

Which command send output to both the screen and a file at the same time?

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.


1 Answers

Use tee to direct it straight to screen instead of stdout

$ var=$(echo hi | tee /dev/tty) hi $ echo $var hi 
like image 183
123 Avatar answered Oct 26 '22 00:10

123