Create Multiline Strings in Bash

Here's how you can handle multiline strings in bash scripts.
Warp Terminal

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:

  1. Using heredocs
  2. 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

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

echo "$str"

If you execute the above script, the output will look like this:

Use heredocs to create multiline strings in bash

2. Using printf

With the printf command, you can print multiline strings by using a newline character (\n) as shown here:


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.

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"
Use the printf command to print multiline strings in bash

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:

Bash Split String Example Explained
Here’s a quick little bash tip about splitting strings based on a specified delimiter.

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

Bash Basics Series #6: Handling String Operations
In this chapter of the Bash Basics series, learn to perform various common string operations like extracting, replacing and deleting substrings.

I hope you will find this guide helpful.

About the author
Sagar Sharma

Sagar Sharma

A software engineer who loves to write about his experience with Linux. While reviving my crashed system, you can find me reading literature, manga, or watering my plants.

Become a Better Linux User

With the FOSS Weekly Newsletter, you learn useful Linux tips, discover applications, explore new distros and stay updated with the latest from Linux world


Great! You’ve successfully signed up.

Welcome back! You've successfully signed in.

You've successfully subscribed to It's FOSS.

Success! Check your email for magic link to sign-in.

Success! Your billing info has been updated.

Your billing was not updated.