New line in bash variables
You need to double quote it (and you should double quote variables in most case):
echo "$LS"
But don't use echo to print variables content, using printf instead:
printf '%s\n' "$LS"
The newlines are in the variable. LS=$(ls -1)
sets the variable LS
to the output of ls -1
(which produces the same output as ls
, by the way, except when the output goes to a terminal), minus trailing newlines.
The problem is that you're removing the newlines when you print out the value. In a shell script, $LS
does not mean “the value of the variable LS
”, it means “take the value of LS
, split it into words according to IFS
and interpret each word as a glob pattern”. To get the value of LS
, you need to write "$LS"
, or more generally to put $LS
between double quotes.
echo "$LS"
prints the value of LS
, except in some shells that interpret backslash characters, and except for a few values that begin with -
.
printf "$LS"
prints the value of LS
as long as it doesn't contain any percent or backslash character and (with most implementations) doesn't start with -
.
To print the value of LS
exactly, use printf %s "$LS"
. If you want a newline at the end, use printf '%s\n' "$LS"
.
Note that $(ls)
is not, in general, the list of files in the current directory. This only works when you have sufficiently tame file names. To get the list of file names (except dot files), you need to use a wildcard: *
. The result is a list of strings, not a string, so you can't assign it to a string variable; you can use an array variable files=(*)
in shells that support them (ksh93, bash, zsh).
For more information, see Why does my shell script choke on whitespace or other special characters?