0

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

James
  • 1

1 Answers1

1

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

Chris Davies
  • 116,213
  • 16
  • 160
  • 287