将多行字符串回显到文件 bash 中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39277019/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Echo multiline string into file bash
提问by MarksCode
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:
我想将一些带有换行符的文本回显到我的 bash 脚本中的文件中。我可以这样做,echo -e "line1 \n line2 \n"
但是当文本变得很长时,这将变得不可读。我尝试使用换行符执行以下操作:
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?
然而,当插入文本时,没有放置换行符,所以整个事情都在一行上。有没有办法用换行符回显文本,同时使 bash 脚本可读?
回答by Tom Fenech
If you want to use echo
, just do this:
如果您想使用echo
,只需执行以下操作:
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.
即用引号将整个字符串包裹起来,不要尝试转义换行符。看起来您不想扩展字符串中的任何 shell 参数,因此请使用单引号。
Alternatively it's quite common to use a heredoc for this purpose:
或者,为此目的使用 heredoc 是很常见的:
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.
请注意,在这种情况下将扩展 shell 参数。使用 bash,您可以在第一行使用<<'EOF'
而不是<<EOF
避免这种情况。