Search code examples
bashnewlinestring-concatenation

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?


Solution

  • 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".