Your command var=$(ls -1)
works fine. Try echo "$var"
(with double quotes).
In echo $var
, bash is reading $var
and passing each word in as an argument to echo
. It treats spaces and line breaks the same way. Using double quotes causes bash to treat $var
as a single argument, rather than reformatting it.
As mklement0 mentioned, the expansion of $var
that happens here is called word splitting. Search for "Word Splitting" in man bash
for more information. The IFS
variable (also in man bash
) controls what characters bash uses to perform word splitting.