Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate strings with newline in bash?

I have seen Concatenating two string variables in bash appending newline - but as i read it, the solution is:

echo it like this with double quotes:

... but I cannot seem to reproduce it - here is an example:

$ bash --version
GNU bash, version 5.0.17(1)-release (x86_64-pc-linux-gnu)

$ mystr=""
$ mystr="${mystr}First line here\n"
$ mystr="${mystr}Second line here\n"
$ mystr="${mystr}Third line here\n"
$ echo $mystr
First line here\nSecond line here\nThird line here\n

So far, as expected - and here is the double quotes:

$ echo "$mystr"
First line here\nSecond line here\nThird line here\n

Again I do not get the new lines - so the advice "echo it like this with double quotes" seems not to be correct.

Can anyone say accurately, how do I get proper newlines output (not just \n) when concatenating strings in bash?

like image 262
sdbbs Avatar asked Sep 01 '25 22:09

sdbbs


2 Answers

Add a newline, not two characters \ and n, to the string.

mystr=""
mystr+="First line here"$'\n'
mystr+="Second line here"$'\n'
mystr+="Third line here"$'\n'
echo "$mystr"

Or you can interpret \ escape sequences - with sed, with echo -e or with printf "%b" "$mystr".

like image 80
KamilCuk Avatar answered Sep 03 '25 12:09

KamilCuk


You should do

nabil@LAPTOP:~$ echo -e $mystr
First line here
Second line here
Third line here

nabil@LAPTOP:~$

You can find the other options in the man

 -e     enable interpretation of backslash escapes
like image 23
Nabil Avatar answered Sep 03 '25 11:09

Nabil