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?
printf "%s\n" $LS
would do it. – Jeff Schaller Jul 09 '15 at 12:39wc
and other commands:wc -l <<< "$LS"
– Wizard79 Jul 09 '15 at 12:43printf '%s\n' "$LS"
if you want to see newline. That's mis-typing, fixed it! – cuonglm Jul 09 '15 at 13:03$(git diff)
, which has mentions of\n
that I've added, which subsequently get interpreted as a newline byecho
. – cnst Nov 05 '15 at 13:51printf
instead of echo, as echo makes no distinction between actual newlines and \n literals.V=$(printf 'line1:test\\ntest\\n\nline2\n') ; printf '%s\n' "$V"
– cnst Nov 05 '15 at 14:03