Here Documents
Passing Multi-Line Input with Here Documents and Herestrings¶
When scripting, you often need to pass multi-line input to commands without relying on external files. Bash provides two mechanisms for this: here documents and herestrings. Both allow you to embed input directly into a command’s standard input stream, but they differ in how they handle variable expansion and syntax.
Here Documents¶
A here document (also called a "here doc") sends multi-line text to a command’s standard input. It begins with << followed by a delimiter (e.g., EOF), and ends when the delimiter is encountered on a line by itself. The delimiter is case-sensitive and must match exactly.
Syntax¶
Example: Using cat with a Here Document¶
Output:
Key Notes¶
- The delimiter line must not have leading spaces.
- Variables in the here document are expanded (e.g.,
$HOMEbecomes the home directory path). - A newline is added after the last line of input unless explicitly suppressed.
Herestrings¶
A herestring is similar to a here document but uses <<'DELIMITER' or <<"DELIMITER"`" to disable variable expansion. This makes it ideal for passing literal text, such as configuration snippets or raw data, without unintended substitutions.
Syntax¶
Example: Using echo with a Herestring¶
Output:
Key Notes¶
- The delimiter is enclosed in quotes (
'or"), which prevents variable expansion and command substitution. - Herestrings are specific to Bash and not supported in all shells.
When to Use Each¶
| Feature | Here Document | Herestring |
|---|---|---|
| Variable Expansion | ✅ Enabled | ❌ Disabled |
| Syntax | <<DELIMITER |
<<'DELIMITER' |
| Use Case | Dynamic input | Literal data |
Key takeaways¶
- Use here documents for multi-line input that requires variable expansion (e.g., generating config files).
- Use herestrings for literal text where variables and commands should remain unprocessed (e.g., logging or debugging).
- Always ensure the delimiter matches exactly and is placed on a line by itself.
- Herestrings are Bash-specific; avoid them in scripts intended for other shells.