
When you think of strings in bash, you think of a word or a combination of a few words. Basically, a single line.
But what if you want to use a multiline strings in bash? I mean you have some text that goes over several lines.
Well, in this tutorial, I will walk you through two ways to create multiline strings in bash:
- Using heredocs
- Using printf
Let's start with the first one.
1. Using heredocs
Heredocs allow you to create multiline strings by using the cat command and a delimiter after the redirection operator (<<
). Sounds complex? Here's a simple syntax:
string_var=$(cat <<DELIMITER
This is a
multiline
string.
DELIMITER
)
echo "$string_var"
For example, here, I created a str
variable and used END
as a delimiter to create a multiline string:
str=$(cat <<END
Sagar Sharma
from
itsFOSS.com
END
)
echo "$str"
If you execute the above script, the output will look like this:

2. Using printf
With the printf command, you can print multiline strings by using a newline character (\n
) as shown here:
multiline_string="String-1\nString-2\nString-3."
Once after assigning multiline strings to a variable, you use the printf command with the -e
flag to enable the interpretation of backslash escape sequences.
multiline_string="String-1\nString-2\nString-3."
printf -e "$multiline_string"
For example, here, I created str_var
to hold 3 multiline strings and then execute the script to show its outcome:
str_var="Greetings\nFrom\nSagar Sharma."
echo -e "$str_var"

More on strings in bash
Ever wondered how you split a string in bash? Well, to help you with this, we wrote a detailed guide on how to split strings in bash:

But if you are a beginner and want to know the basics of handling strings in bash, then refer to the following tutorial:

I hope you will find this guide helpful.
It's FOSS turns 13! 13 years of helping people use Linux โค๏ธ
And we need your help to go on for 13 more years. Support us with a Plus membership and enjoy an ad-free reading experience and get a Linux eBook for free.
To celebrate 13 years of It's FOSS, we have a lifetime membership option with reduced pricing of just $76. This is valid until 25th June only.
If you ever wanted to appreciate our work with Plus membership but didn't like the recurring subscription, this is your chance ๐