Search This Blog

2013-06-12

Appending Multiple Lines to End of File in Bash

How do you easily add multiple lines to the end of a file?

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

Using the "Here Tag" (in this case EOF) you can tell the shell that you're going to be entering a multi-line string until you hit a string of characters again. You can call it anything but typically its EOF.

The <<EOF part tells the shell you're going to enter multi-lines until you hit EOF, it will wait until it sees EOF again and must match EOF exactly

Important Note About EOF Placement

It is important to note that the EOF marker MUST appear with no spaces preceding it. Even if you're trying to format code to look nicely any preceeding spaces will cause the error "delimited by end-of-file wanted eof"

Keep in mind the following if you want to indent:
If you write <<-EOF you may indent it, but it must be indented with Tab characters, not spaces. So it still might not end up even with the block of code.

Reference:
http://askubuntu.com/questions/485567/unexpected-end-of-file
http://stackoverflow.com/questions/18660798/here-document-delimited-by-end-of-file

Also look out for spaces after the EOF.
You can use either
cat -e file
or
cat -A file
to take a look at special characters such as end of line characters to see anything that looks out of place.

Reference:
http://en.wikipedia.org/wiki/Here_document#Unix-Shells
http://stackoverflow.com/questions/4990172/how-to-append-several-lines-of-text-in-a-file-using-a-shell-script
http://www.linuxjournal.com/content/bash-input-redirection

No comments:

Post a Comment