A Here Document, also known as heredoc, is a feature in Bash (and other shells) that allows you to include multiline input within a script or command directly, without the need for external files. It provides a convenient way to specify blocks of text or data inline within a script.
In Bash, a Here Document is defined using the <<
symbol followed by a delimiter of your choice. The text or data enclosed between the delimiters is treated as input and can be assigned to a variable, used as input for a command, or redirected to a file.
Here’s a basic syntax example:
command <<DELIMITER
text
...
DELIMITER
Let’s break down the components:
command
: The command that will process or receive the here document.<<DELIMITER
: The opening delimiter that marks the start of the here document.DELIMITER
can be any word you choose as long as it is not a valid shell variable or command name.text
: The actual content of the here document. It can span multiple lines and include any text or data you want to provide.
Once the here document is defined, Bash treats the text as input to the specified command or operation. The command or operation can be anything that accepts input, such as a command that reads from standard input (stdin
) or a variable assignment.
Here’s an example of a Here Document being used with the cat
command to display multiline text:
cat <<END
This is a Here Document example.
It allows for multiline input
without the need for external files.
END
When this script is executed, the cat
command receives the Here Document text as input and displays it as output:
This is a Here Document example.
It allows for multiline input
without the need for external files.
Here Documents are particularly useful when you need to provide extensive input or include formatted text blocks within a script without relying on separate files or complex concatenation operations.