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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With