Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash - How to print multi line strings (with '\n') using printf

i'm trying to print a multi line strings in printf this way

printf "hi\n"
printf "next line here\n"

I can't do the following

text_content="
hi
next line here
"

printf $text_content

Is there any other way?

like image 478
wolfgang Avatar asked Sep 03 '15 09:09

wolfgang


People also ask

How do I print a multiline string in bash?

Use printf to Make Multi-Line String in Bash We can use printf with the new line character and redirect the output to a file using > . The content in the file does not have extra spaces.

How do I echo multiple lines in bash?

To add multiple lines to a file with echo, use the -e option and separate each line with \n. When you use the -e option, it tells echo to evaluate backslash characters such as \n for new line. If you cat the file, you will realize that each entry is added on a new line immediately after the existing content.

How do I echo a newline in bash?

Printing Newline in Bash The most common way is to use the echo command. However, the printf command also works fine. Using the backslash character for newline “\n” is the conventional way. However, it's also possible to denote newlines using the “$” sign.


1 Answers

Quoting the variable should do the trick. In your example, however, you are getting double newlines.

printf "$text_content"
like image 184
Reuben L. Avatar answered Oct 14 '22 03:10

Reuben L.