如何使用shell脚本在文件中附加几行文本

时间:2022-04-18 23:59:55

I want to write several lines (5 or more) to a file I'm going to create in script. I can do this by echo >> filename. But I would like to know what the best way to do this?

我想要写几行(5个或更多)到我将要创建的一个文件。我可以通过echo >>文件名做到这一点。但是我想知道最好的方法是什么?

2 个解决方案

#1


78  

You can use a here document:

你可以使用“here”文件:

cat <<EOF >> outputfile
some lines
of text
EOF

#2


4  

I usually use the so-called "here-document" Dennis suggested. An alternative is:

我通常使用丹尼斯建议的所谓“here-document”。另一种方法是:

(echo first line; echo second line) >> outputfile

This should have comparable performance in bash, as (....) starts a subshell, but echo is 'inlined' - bash does not run /bin/echo, but does the echo by itself.

这应该有类似的性能在bash中,作为一个shell(....)开始,但回声“内联”——bash并不/bin/echo运行,但是回声。

It might even be faster because it involves no exec().

它甚至可能更快,因为它不涉及exec()。

This style is even more useful if you want to use output from another command somewhere in the text.

如果您想使用文本中某处的另一个命令的输出,那么这种样式会更有用。

#1


78  

You can use a here document:

你可以使用“here”文件:

cat <<EOF >> outputfile
some lines
of text
EOF

#2


4  

I usually use the so-called "here-document" Dennis suggested. An alternative is:

我通常使用丹尼斯建议的所谓“here-document”。另一种方法是:

(echo first line; echo second line) >> outputfile

This should have comparable performance in bash, as (....) starts a subshell, but echo is 'inlined' - bash does not run /bin/echo, but does the echo by itself.

这应该有类似的性能在bash中,作为一个shell(....)开始,但回声“内联”——bash并不/bin/echo运行,但是回声。

It might even be faster because it involves no exec().

它甚至可能更快,因为它不涉及exec()。

This style is even more useful if you want to use output from another command somewhere in the text.

如果您想使用文本中某处的另一个命令的输出,那么这种样式会更有用。