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
Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
makccr
  • 21
  • 5
  • 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? – Benjamin W. Aug 26 '19 at 00:29

1 Answers1

2

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

text=(lineOne\\n lineTwo\\n lineThree)
echo -e "${text[@]}" >> text.txt
vmorsell
  • 79
  • 5
  • Hey, that totally did worked for me. Thx! – makccr Aug 26 '19 at 00:12
  • 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. – makccr Aug 26 '19 at 00:13
  • Good to hear @makccr. The `-e` flag enables interpretation of backslash escapes. The [`printf`](https://stackoverflow.com/a/15692004/9734785) 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 :) – vmorsell Aug 26 '19 at 00:48
  • 1
    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. – Gordon Davisson Aug 26 '19 at 00:54