Bash Shell Quoting – How to Handle New Lines in Bash Variables

bashquotingshell

I'm trying to store multiple lines in a bash variable, but it doesn't seem to work.

For example, if I list /bin one file per line and store it in $LS, then I pass $LS as stdin to wc, it always returns 1:

$ ls -1 /bin | wc -l
134
$ LS=$(ls -1 /bin); wc -l <<< $LS
1

If I try to output to screen, I get various results: echo prints all the lines on a single line, while printf prints only the first line:

#!/bin/bash
LS=$(ls -1 /bin)
echo $LS
printf $LS

So, a bash variable can contain multiple lines?

Best Answer

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"
Related Question