How to define multiline string variable in shell?

In your bash/shell scripting experience you may face scenario where you need to define multi line string variable. Here is multiple ways to define multi line string variable in shell.

Method 1: Combine Multiline with \n like below and echo with -e option

method1="This is line no.1\nThis is line no.3\nThis is line no.3"
echo -e $method1

Output:

This is line no.1
This is line no.3
This is line no.3
-eEnable interpretation of backslash escape sequences .

Method 2: define multiline string in shell variable line below.

method2="This is line no.1
This is line no.2
This is line no.3"
echo "$method2"

Output:

This is line no.1
This is line no.3
This is line no.3

Method 3: Heredoc is more convenient for this purpose.

read -r -d '' MULTI_LINE_VAR << EOM
Print line 1.
Print line 2.
Print line 3
EOM

Note: Please don’t forgot quotes around the variable else you won’t see the characters in newline.

echo "$MULTI_LINE_VAR"

I have listed a few methods to define multiline shell variables. What is your preferred way to print multiline strings in the shell?

,
(Visited 23,749 times, 849 visits today)