Using Here Documents in Linux


cat <<EOF>/tmp/newfile

This is the contents of the here document
It can span multiple lines
A here document says to take all of this text up to the terminating
characters (which in this case are the characters E, O, and F.
I can chose any character string I want to. As soon as the script sees
these characters at the beginning of a line, all by itself with no
trailing whitespace, it will then terminate creating the here document.
Note that I am taking all this text and saving it in the document
called /tmp/newfile. That’s all I have for now, the next line
will contain the magical 3 characters:
EOF

Now you can use the new file however you need:
cat /tmp/newfile

Here is a copy of the man page on here documents. You can bring this up
on your system by looking up “Here Documents” in the “bash” man page
(man bash, then type /Here Documents):


Here Documents This type of redirection instructs the shell to read input from the current source until a line containing only word (with no trailing blanks) is seen. All of the lines read up to that point are then used as the standard input for a command. The format of here-documents is: <<[-]word here-document delimiter No parameter expansion, command substitution, arithmetic expansion, or pathname expansion is performed on word. If any characters in word are quoted, the delimiter is the result of quote removal on word, and the lines in the here-document are not expanded. If word is unquoted, all lines of the here-document are subjected to parameter expansion, com- mand substitution, and arithmetic expansion. In the latter case, the character sequence \ is ignored, and \ must be used to quote the characters \, $, and '. If the redirection operator is <<-, then all leading tab characters are stripped from input lines and the line containing delimiter. This allows here-documents within shell scripts to be indented in a natural fashion.

Leave a Comment