Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

redirect command output into variable and standard output in ksh

Tags:

I have some shell command. I would like to write the output to the standard output and save it into variable as well. I'd like to solve it with one command. I have tried these things.

ls > $VAR          # redirects the output to file which name is stored in $VAR ls | tee -a $VAR   # writes to standard output as well as in file which name is stored in $VAR VAR=`ls`           # output into $VAR, but it is not sent to standard output VAR=`ls`;echo $VAR # ok, it works but these are two commands 

Any idea?

like image 323
Attila Zobolyak Avatar asked Oct 26 '11 10:10

Attila Zobolyak


People also ask

How do you redirect output of a command to 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 ...] arg1 arg2 ...'

Can we redirect the output of a command to a file and display at the same time?

Redirecting output to Multiple files and screen: If you want to redirect the screen output to multiple files, the only thing you have to do is add the file names at the end of the tee command.


2 Answers

How about:

VAR=$(ls | tee /dev/tty) 
like image 155
Gary Barker Avatar answered Sep 22 '22 21:09

Gary Barker


great answer from @Gary_Barker, but this isn't possible on all systems.

On our teamcity there isn't a char-console. And there is another little problem.

If I use

VAR=$(ls -1); echo $VAR

it isn't the same like ls -1

My solution works, if it doesn't matter, that the output comes from error pipe.

VAR=$(ls -1 | tee >&2)

like image 37
S.W.Joerns Avatar answered Sep 22 '22 21:09

S.W.Joerns