How to Use Heredoc in Bash: Syntax and Examples
In bash, use
heredoc to create multiline strings or input by typing <<DELIMITER followed by the text and ending with the same DELIMITER on a line alone. This lets you easily pass blocks of text to commands or variables without quotes or escapes.Syntax
The basic syntax of a heredoc in bash is:
<<DELIMITER: Starts the heredoc, whereDELIMITERis a word you choose to mark the end.- Lines of text: The content you want to include.
DELIMITER: The same word on a line by itself ends the heredoc.
You can use quotes around DELIMITER to control variable expansion inside the heredoc.
bash
cat <<EOF This is line 1 This is line 2 EOF
Example
This example shows how to use heredoc to print multiple lines with cat and how variable expansion works inside it.
bash
name="Alice"
cat <<EOF
Hello, $name!
Welcome to heredoc in bash.
EOFOutput
Hello, Alice!
Welcome to heredoc in bash.
Common Pitfalls
Common mistakes include:
- Not placing the ending
DELIMITERalone on its line (no spaces or tabs allowed). - Using quotes around
DELIMITERchanges variable expansion behavior. - Indentation before the ending
DELIMITERwill cause the heredoc to not end properly.
Example of wrong and right usage:
bash
# Wrong: ending delimiter indented cat <<EOF Line 1 EOF # Right: ending delimiter alone cat <<EOF Line 1 EOF
Quick Reference
| Feature | Description |
|---|---|
<| Start heredoc, DELIMITER marks end | |
| DELIMITER | Must be alone on line to end heredoc |
| "DELIMITER" | No variable expansion inside heredoc |
| 'DELIMITER' | No variable expansion inside heredoc |
| <<-DELIMITER | Allows tab-indented end delimiter |
Key Takeaways
Use <
Variable expansion happens unless DELIMITER is quoted.
The ending delimiter must not have spaces or tabs before it unless using <<-.
Heredoc is useful for multiline strings or feeding input to commands.
Use <<-DELIMITER to allow tabs before the ending delimiter for cleaner indentation.