1

I'm on the latest version of macOS with bash 5.0 installed. I'm trying to write a bash script that will write out a multiple-line text document using variables & the echo program.

I have tried adding a newline character (\n) at multiple different places in the script, but I can't seem to get that to work.

text=(
lineOne
lineTwo
lineThree
)

echo "${text[@]}" >> text.txt

I'm thinking that I should be able to, using the echo program, output a file with multiple lines, since, when you remove the variables and just run echo on its own, it will create new lines automatically. In my case what I'm getting is:

lineOne lineTwo lineThree

What I'm hoping for is:

lineOne
lineTwo
lineThree
1
  • Are you asking about printing array elements on separate lines (text is an array!), or do you want to know how to store a multiline string in a bash variable? Commented Aug 26, 2019 at 0:29

1 Answer 1

3

Try adding the -e flag and use \\n for line breaks.

text=(lineOne\\n lineTwo\\n lineThree)
echo -e "${text[@]}" >> text.txt
Sign up to request clarification or add additional context in comments.

4 Comments

Hey, that totally did worked for me. Thx!
If you don't mind my asking, what does the -e flag actually do? I've seen it pop up a few times, but it doesn't show up in my man page when I open it.
Good to hear @makccr. The -e flag enables interpretation of backslash escapes. The printf way of doing this is far nicer though. You should go for that solution so you don't have to clutter your array with newline characters :)
I don't recommend using echo -e, since different versions of echo (or even the same version running in different situations) behave differently. Some versions, for example, will print "-e" as part of the output. Use printf instead.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.