Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Echo multiline string into file bash

Tags:

bash

I want to echo some text that has newlines into a file in my bash script. I could just do echo -e "line1 \n line2 \n" but that would become unreadable when the text becomes very long. I tried doing the following instead with line breaks:

echo -e "[general]\
    state_file = /var/lib/awslogs/agent-state\
    [/var/log/messages]\
    file = /var/log/messages\
    log_group_name = /var/log/messages\
    log_stream_name = {ip_address}\
    datetime_format = %b %d %H:%M:%S\

However, while the text was inserted, no newlines were placed so the whole thing was on one line. Is there anyway to echo text with newlines while also making the bash script readable?

like image 939
MarksCode Avatar asked Sep 01 '16 16:09

MarksCode


1 Answers

If you want to use echo, just do this:

echo '[general]
state_file = /var/lib/awslogs/agent-state
[/var/log/messages]
file = /var/log/messages
log_group_name = /var/log/messages
log_stream_name = {ip_address}
datetime_format = %b %d %H:%M:%S'

i.e. wrap the whole string in quotes and don't try and escape line breaks. It doesn't look like you want to expand any shell parameters in the string, so use single quotes.

Alternatively it's quite common to use a heredoc for this purpose:

cat <<EOF
[general]
state_file = /var/lib/awslogs/agent-state
[/var/log/messages]
file = /var/log/messages
log_group_name = /var/log/messages
log_stream_name = {ip_address}
datetime_format = %b %d %H:%M:%S
EOF

Note that shell parameters will be expanded in this case. Using bash, you can use <<'EOF' instead of <<EOF on the first line to avoid this.

like image 55
Tom Fenech Avatar answered Oct 23 '22 16:10

Tom Fenech