15

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?

1
  • 1
    Remove \ from end of lines
    – anubhava
    Commented Sep 1, 2016 at 16:56

1 Answer 1

27

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.

2
  • note: with double quotes, shell parameters are expanded as well
    – YakovL
    Commented Nov 20, 2021 at 15:56
  • 2
    That one helped! <<'EOF' thx!
    – f b
    Commented Mar 4, 2022 at 12:26

Not the answer you're looking for? Browse other questions tagged or ask your own question.