Reputation: 749
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?
Upvotes: 26
Views: 77100
Reputation: 2017
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.
Upvotes: 0
Reputation: 31
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)
Upvotes: 3