Multiline Echo in Bash
-
Use the Keyword
cat
in Bash to Create Multline Output in Bash -
Use the Keyword
print
to Create Multline Output in Bash
Sometimes we need to work with multiline outputs. In a general programming language, we can create a new line using the \n
; this task is a bit complex in Bash scripting.
We can’t directly use anything like \n
as we did on another programming language. This article will discuss how to create a multiline output on Bash.
Also, to make the topic easier, we will use some examples with proper explanations. Now, we are going to see two methods here.
Use the Keyword cat
in Bash to Create Multline Output in Bash
We can also create multiline output with the keyword cat
. You can follow the example code to create a multiline output with this method.
cat <<'END'
This is the first line,
This is the second line
This is the third line
END
Looking at the code, you can see that we used the line cat <<'END'
at the beginning of the code. This will continue showing output until the END
.
Remember, you can choose any tag with the line cat <<'END'
, but you need to end with the same tag you used at the beginning. So we can say the general syntax is:
cat <<'YOUR_TAG'
-
- Your output here
-
YOUR_TAG
You will get the below output after you run the example code.
This is the first line,
This is the second line
This is the third line
Use the Keyword print
to Create Multline Output in Bash
We can also get the same output as our previous example using the keyword print
. You can follow the below example to create a multiline output.
printf '%s\n' \
'This is the first line,' \
'This is the second line' \
'This is the third line'
So you can use this general syntax for this purpose.
printf '%s\n' \
'YOUR FIRST LINE' \
'YOUR SECOND LINE' \
'YOUR THIRD LINE'
As you can see on the code, we started with '%s\n'
. This is to show the output in a new line each time the ''
ends.
Besides, we need to use the symbol \
to indicate a new line. Remember you have to put everything in a quote; otherwise, it will count as a single line.
You will get the below output after you run the example code.
This is the first line,
This is the second line
This is the third line
All the codes used in this article are written in Bash. It will only work in the Linux Shell environment.
Aminul Is an Expert Technical Writer and Full-Stack Developer. He has hands-on working experience on numerous Developer Platforms and SAAS startups. He is highly skilled in numerous Programming languages and Frameworks. He can write professional technical articles like Reviews, Programming, Documentation, SOP, User manual, Whitepaper, etc.
LinkedIn