0
0
Bash-scriptingHow-ToBeginner · 3 min read

How to Use Here Document in Bash: Syntax and Examples

In Bash, a here document lets you feed multiple lines of input to a command using the syntax <<EOF followed by the input lines and ending with EOF. It is useful for providing multiline strings or commands directly inside scripts.
📐

Syntax

A here document starts with <<WORD where WORD is a delimiter you choose (commonly EOF). The shell reads input until it finds a line with only WORD. This input is then passed as standard input to the command.

  • command <<EOF: Begins the here document for command.
  • Lines of input: The text you want to send to the command.
  • EOF: The delimiter line that ends the input.
bash
command <<EOF
line1
line2
EOF
💻

Example

This example uses cat to print multiple lines using a here document. It shows how to send multiline text directly to a command.

bash
cat <<EOF
Hello, this is line one.
This is line two.
EOF
Output
Hello, this is line one. This is line two.
⚠️

Common Pitfalls

Common mistakes include:

  • Not matching the ending delimiter exactly (case sensitive, no extra spaces).
  • Indenting the delimiter line, which stops the here document prematurely.
  • Using quotes around the delimiter changes how variables are expanded inside the here document.

Example of wrong and right usage:

bash
# Wrong: delimiter indented, so here document ends early
cat <<EOF
Line 1
  EOF

# Right: delimiter must be at start of line
cat <<EOF
Line 1
EOF
Output
Line 1
📊

Quick Reference

Tips for using here documents:

  • Use < without quotes to allow variable expansion.
  • Use <<"EOF" or <<'EOF' to prevent variable expansion.
  • The delimiter must be alone on its line with no spaces or tabs.
  • Indentation before the delimiter breaks the here document unless you use <<-EOF which allows tab-indented delimiters.

Key Takeaways

A here document feeds multiline input to a command using << followed by a delimiter.
The delimiter line must match exactly and be at the start of the line with no spaces.
Quoting the delimiter controls whether variables inside the here document are expanded.
Indenting the delimiter or mismatching it causes errors or unexpected behavior.
Here documents are useful for embedding multiline text or commands directly in scripts.