How to assign a multiple line value to a bash variable
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
When you initialize FOO
you should use line breaks: \n
.
FOO="This is line 1\nThis is line 2\nThis is line 3"
Then use echo -e
to output FOO
.
It is important to note that
\n
inside"..."
is NOT a line break, but literal\
, followed by literaln
. It is only when interpreted byecho -e
that this literal sequence is converted to a newline character. — wise words from mklement0
#!/bin/bash
FOO="This is line 1\nThis is line 2\nThis is line 3"
echo -e $FOO
Output:
This is line 1
This is line 2
This is line 3