How to write multiple line strings using Bash with variables on Linux?

LinuxOperating SystemOpen Source

Setting a variable to a single line in bash and then printing it to console is a fairly easy process, but if we want to write multiple line strings using Bash then we have to consider different approaches.

In total there are three approaches that we can make use of, all of these are mentioned below with examples.

Multiline with \n

We can make use of the \n symbol to make sure that whatever string we write has a newline in between them. With this approach we can write as many lines as possible, we just need to write the same number of \n’s in the string.

Example

approach1="First Line Text\nSecond Line Text\nThird Line Text"
echo $approach1

Output

sh-3.2# ./sample.sh
First Line Text
Second Line Text
Third Line Text

Multiline String

Just make sure to put the entire string in double quotes.

Example

approach2="First Line Text
Second Line Text
Third Line Text"
echo "$approach2"

Output

sh-3.2# ./sample.sh
First Line Text
Second Line Text
Third Line Text

Heredoc

Use the Heredoc approach.

Example

read -r -d '' MULTI_LINE_VAR_STRING << EOM
First Line Text
Second Line Text
Third Line Text
EOM

echo $MULTI_LINE_VAR_STRING

Output

sh-3.2# ./sample.sh
First Line Text
Second Line Text
Third Line Text
raja
Published on 31-Jul-2021 12:03:19
Advertisements