39

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?

2 Answers 2

103

You can use a here document:

cat <<EOF >> outputfile
some lines
of text
EOF
Sign up to request clarification or add additional context in comments.

3 Comments

+1: But works only with fixed text, not generated in script. No vars substitution etc. right?
@Valentin: It will do variable, arithmetic and command substitution unless you suppress it by quoting the opening delimiter like this, for example: 'EOF'.
Ive been unable to get the - modifier to work. AS n cat <<-EOF >> out which should strip whitespace
6

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

(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.

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

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

1 Comment

to avoid creating a subshell, you can use braces for grouping. Just remember to end the command list with a semicolon and separate the braces with spaces -- { echo first; echo second; } >> outputfile

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.