如何使用带有变量的 Bash 编写多行字符串?
如何使用 BASH 在名为 myconfig.conf
的文件中写入多行?
#!/bin/bash
kernel="2.6.39";
distro="xyz";
echo <<< EOL
line 1, ${kernel}
line 2,
line 3, ${distro}
line 4
line ...
EOL >> /etc/myconfig.conf;
cat /etc/myconfig.conf;
How can I write multi-lines in a file called myconfig.conf
using BASH?
#!/bin/bash
kernel="2.6.39";
distro="xyz";
echo <<< EOL
line 1, ${kernel}
line 2,
line 3, ${distro}
line 4
line ...
EOL >> /etc/myconfig.conf;
cat /etc/myconfig.conf;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
语法 (
<<<
) 和使用的命令 (echo
) 错误。正确的是:
此结构被称为 此处文档,可以在 Bash man 中找到
man --pager='less -p "\s*Here Documents"' bash
下的页面。The syntax (
<<<
) and the command used (echo
) is wrong.Correct would be:
This construction is referred to as a Here Document and can be found in the Bash man pages under
man --pager='less -p "\s*Here Documents"' bash
.这就是你想要的。
this does what you want.
如果您不想替换变量,则需要用单引号将 EOL 引起来。
前面的例子:
If you do not want variables to be replaced, you need to surround EOL with single quotes.
Previous example:
Heredoc 解决方案当然是最常见的方法。其他常见的解决方案有:
和
和
The heredoc solutions are certainly the most common way to do this. Other common solutions are:
and
and
我正在使用 Mac OS 并在 SH 脚本 中编写多行,以下代码对我有用
请不要忘记根据需要将 chmod 分配给脚本文件。
我用过
I'm using Mac OS and to write multiple lines in a SH Script following code worked for me
Please don't forget to assign chmod as required to the script file.
I have used
下面的机制有助于将多行重定向到文件。将完整的字符串保留在
"
下,以便我们可以重定向变量的值。a.txt
的内容是b.txt
的内容是Below mechanism helps in redirecting multiple lines to file. Keep complete string under
"
so that we can redirect values of the variable.Content of
a.txt
isContent of
b.txt
is在我的用例中,我必须使用以下内容:
这是因为如果未定义变量,我不想将空换行符写入文件。这种方法的好处是,如果需要,您可以在块内编写各种任意逻辑。
当然,如果您想附加,您也可以在此处使用
>>
而不是像其他答案中那样使用>
。In my usecase I had to use the following:
This because I did not want to write empty newlines to the file if the variables were not defined. The nice thing about this method is that you can write all kinds of arbitrary logic within the block if necessary.
And ofcourse, if you would like to append, you can also use
>>
here instead of>
like you would in the other answers.我通常将模板放入文件中并使用此模板引擎:
I usually put template in file and use this templating engine:
我认为另一种更简单的方法,但绝对适用于少量行
another simpler way I think but definitely for small number of lines