Bash Scripting – How to Add Newlines into Variables in Bash Script

bashquoting

When I do

str="Hello World\n===========\n"

I get the \n printed out too. How can I have newlines then?

Best Answer

In bash you can use the syntax

str=$'Hello World\n===========\n'

Single quotes preceded by a $ is a new syntax that allows to insert escape sequences in strings.

Also printf builtin allows to save the resulting output to a variable

printf -v str 'Hello World\n===========\n'

Both solutions do not require a subshell.

If in the following you need to print the string, you should use double quotes, like in the following example:

echo "$str"

because when you print the string without quotes, newline are converted to spaces.

Related Question