简体   繁体   中英

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 ?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM