Bash: Use Echo to Output a Multi-line String


Often you may want to use the echo command to output a multi-line string in Bash.

You can use the following basic syntax to do so:

favorite_teams="
Here are my favorite basketball teams:
Mavs
Spurs
Rockets
"

echo "$favorite_teams"

This particular example saves a multi-line string in a variable named favorite_teams and then uses the echo command with a dollar sign and double quotes around the variable name to output the multi-line string.

The following example shows how to use this syntax in practice.

Example: How to Use Echo to Output a Multi-Line String in Bash

Suppose that we would like to output the following string that contains information about an individual’s favorite basketball teams:

Here are my favorite basketball teams:
Mavs
Spurs
Rockets

We can use the following syntax to do so:

favorite_teams="
Here are my favorite basketball teams:
Mavs
Spurs
Rockets
"

echo "$favorite_teams"

The following screenshot shows how to use this syntax in practice:

Bash echo multiline string

Notice that the string is outputted on multiple lines, just as we specified.

It’s important to note that you must put double quotes around the variable name when using the echo command or else the string will simply be output on one line.

For example, suppose we attempt to use the echo command with no double quotes:

favorite_teams="
Here are my favorite basketball teams:
Mavs
Spurs
Rockets
"

echo $favorite_teams

The following screenshot shows how to use this syntax in practice:

The string is shown on only one line in the output instead of multiple lines since we did not wrap the variable name in double quotes.

This is a common mistake to avoid when attempting to output a multi-line string.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

How to Remove Spaces from String in Bash
How to Get Last Word of a String in Bash
How to Escape Dollar Signs in Bash
How to Split a String Using Multiple Delimiters in Bash

Leave a Reply