molecule molecule - 5 months ago 13
Bash Question

How to assign a multiple line value to a bash variable

I have a variable

FOO
with me that needs to be assigned with a value that will be multiple lines. Something like this,

FOO="This is line 1
This is line 2
This is line 3"


So when I print the value of
FOO
it should give the following output.

echo $FOO
output:
This is line 1
This is line 2
This is line 3


Furthermore, the number of lines will be decided dynamically as I will initialize it using a loop.

The answers that have been shown in the other question using mainly
read -d
is not suitable for me as I am doing intensive string operations and the code format is also important.

Answer

Don't indent the lines or you'll get extra spaces. Use quotes when you expand "$FOO" to ensure the newlines are preserved.

$ FOO="This is line 1 
This is line 2   
This is line 3"
$ echo "$FOO"
This is line 1
This is line 2
This is line 3

Another way is to use \n escape sequences. They're interpreted inside of $'...' strings.

$ FOO=$'This is line 1\nThis is line 2\nThis is line 3'
$ echo "$FOO"

A third way is to store the characters \ and n, and then have echo -e interpret the escape sequences. It's a subtle difference. The important part is that \n isn't interpreted inside of regular quotes.

$ FOO='This is line 1\nThis is line 2\nThis is line 3'
$ echo -e "$FOO"
This is line 1
This is line 2
This is line 3

You can see the distinction I'm making if you remove the -e option and have echo print the raw string without interpreting anything.

$ echo "$FOO"
This is line 1\nThis is line 2\nThis is line 3