Hello i want to ask why when i write
ls -l
there is new line after every row but when i assign it to a variable
myVariable=`ls -l`
and than echo that variable
echo $myVariable
i get everything in concatanated in one row...Thanks
Hello i want to ask why when i write
ls -l
there is new line after every row but when i assign it to a variable
myVariable=`ls -l`
and than echo that variable
echo $myVariable
i get everything in concatanated in one row...Thanks
There are two independent issues arising from this question.
The ls
command is built to act differently when it writes to the terminal and when it writes to a file or pipe. You can see this by comparing these two commands
ls
ls | cat
In the first example, ls
can see it's writing to the terminal and so it formats its output for a human reader. In the second example, ls
can see it's writing to a file or pipe, so it produces one entry per line. You can override the two settings with the -1
or -C
arguments.
When you assign ls -l
to a variable the newlines are kept. However, in your case you're not quoting the variable when you use it so each run of "whitespace" (everything that doesn't print visible characters) is converted to single space. Compare these results
var=$(ls -l); echo $var
var=$(ls -l); echo "$var"
See $VAR vs ${VAR} and to quote or not to quote for lots more detail. Notice also that I've used $(...)
in preference to `...`
. The suggested duplicate answer, understanding backtick explains why.
echo $myvariable
without using double-quotes around the variable, all the newlines and extra spaces are stripped by the shell. useecho "$myvariable"
instead. See the link in @roaima's comment. – cas Apr 25 '16 at 23:45