26

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?

Attila Zobolyak
  • 739
  • 2
  • 10
  • 15
  • Just curious about the 1 line limitation. that makes me thing youre not the root of, of also a user of the system target. I can't figure out why do you have that limitation. Anyway i have posted you a "doyourself" answer. – m3nda Jan 21 '15 at 06:58

3 Answers3

59

How about:

VAR=$(ls | tee /dev/tty)
Gary Barker
  • 1,609
  • 2
  • 15
  • 18
  • Depending on your OS, `var=$(ls | tee /proc/$$/fd/1)` might work too. – glenn jackman Oct 26 '11 at 12:40
  • Even if this is working perfectly, i post you an "do-it-yourself way" example. Im a Linux/bash noob, but i like learn those tips :D – m3nda Jan 21 '15 at 08:13
  • Note that this (tee) only catches STDOUT output and that programs often do not color it (i.e. use `VAR=$(ls --color | tee /dev/tty)` to get coloured output). – rugk Sep 28 '17 at 14:07
3

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)

S.W.Joerns
  • 31
  • 2
0

As i understand, VAR=`ls`;echo $VAR is OK but you don't like because has 2 commands on it.

While @Gary-Barker is working, i have not check on all systems. If you got problem with tee or another, you can build your own ALWAYS.

I don't know if you know that, but a lot of the programs you can use on Linux are just a bunch of code using the small binarys on system. While this is true, there's no sense about use 1 or 2 commans, because the final execution is really a bunch of little ones.

So, if your real problem is that you can only write a single command in your target, you can write your own "app", by making a sh script in /sbin folder an leaving it without .sh extension (because these are excecuted with ./ or sh prefix and not by name)

I wrote that as example:

#!/bin/bash if [ $1 ] then VAR=$*; echo $VAR fi

For this example i have make the file /sbin/varrun. I've tried it with the folling commands with successful (normal) output:

  • varrun ls
  • varrun uname
  • varrun uname -a

Note that i've not used "quotes" on commands with spaces.

m3nda
  • 1,986
  • 3
  • 32
  • 45