Nov 10, 2018

Here document

In computer science, a here document (here-document, heredoc, hereis, here-string or here-script) is a file literal or input stream literal: it is a section of a source code file that is treated as if it were a separate file. The term is also used for a form of multiline string literals that use similar syntax, preserving line breaks and other whitespace (including indentation) in the text.

Here documents originate in the Unix shell, and are found in sh, csh, ksh, Bash and zsh, among others. Here document-style string literals are found in various high-level languages, notably the Perl programming language (syntax inspired by Unix shell) and languages influenced by Perl, such as PHP and Ruby. Other high-level languages such as Python and Tcl have other facilities for multiline strings.

For here documents, whether treated as files or strings, some languages treat it as a format string, allow variable substitution and command substitution inside the literal.

The most common syntax for here documents, originating in Unix shells, is << followed by a delimiting identifier (often EOF or END), followed, starting on the next line, by the text to be quoted, and then closed by the same delimiting identifier on its own line. This syntax is because here documents are formally stream literals, and the content of the document is redirected to stdin (standard input) of the preceding command; the here document syntax is by analogy with the syntax for input redirection, which is < "take input from the output of the following command".
Other languages often use substantially similar syntax, but details of syntax and actual functionality can vary significantly. When used simply for string literals, the << does not indicate indirection, but is simply a starting delimiter convention.

Example:
mysql <<EOF
show tables;
quit
EOF