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

  • 2
    @ThomasDickey I'd suggest this question here is more about (not) using double quotes
    – roaima
    Apr 25 '16 at 22:35
  • The simple answer is that when you echo $myvariable without using double-quotes around the variable, all the newlines and extra spaces are stripped by the shell. use echo "$myvariable" instead. See the link in @roaima's comment.
    – cas
    Apr 25 '16 at 23:45

There are two independent issues arising from this question.

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

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.