Here-Documents and Templating

Here-Documents and Templating in Bash: In the typing pool of an old firm, a manager dictates a letter to a copy typist.

The Analogy: The Copy Typist Taking Dictation

In the typing pool of an old firm, a manager dictates a letter to a copy typist. The manager speaks the text aloud; the typist takes it down and produces a clean page. Two conventions make this work without confusion. The text runs from the moment the manager begins until a specific, agreed closing phrase -- "that is the end of the letter" -- and not one word further. Everything between the opening and that phrase is the body; the phrase itself is never typed.

Most dictation is interpreted as it goes. When the manager says "insert the client's name here" or "put in today's reference number," the typist does not write those words literally -- they look the value up in the file and fill the blank. This is the normal, merge mode: named slots in the dictation are replaced with real values before the letter is finished, so a single dictated template can produce a hundred personalised letters.

Sometimes, though, the manager wants the words typed exactly as spoken, character for character, including a phrase like "insert the client's name here" as literal text -- perhaps because the letter is itself an instruction sheet about how dictation works. The manager says "take this down verbatim," and the typist switches off interpretation entirely: no slots are filled, nothing is looked up, every character lands on the page as spoken. The manager may also indent the notes on their pad for readability and ask the typist to ignore the left-margin tabs, so the finished letter is flush to the margin even though the notes were stepped in.

Everything hinges on that closing phrase. If the manager trails off and never says the exact agreed words, the typist sits with pen poised, waiting for an ending that never comes, and the whole letter is never finished -- the office simply stalls. And the phrase must be said cleanly: mumble it, tack on an extra word, or bury it mid-sentence, and the typist does not recognise it as the end and keeps transcribing the supposed ending as more body text. A here-document lives or dies by its terminator in exactly this way.


Syntax or Core Structure

A here-document feeds a block of literal text to a command's standard input. You write <<WORD, then the lines of the body, then WORD alone on its own line to close it. By default the body behaves like a double-quoted string: $variable references and $( ... ) command substitutions are expanded, but the text is otherwise passed through untouched.

#!/usr/bin/env bash
set -euo pipefail

name="Ada"
role="engineer"

cat <<EOF
Hello, $name.
Your role is: $role.
Task count: $(( 3 + 4 )).
EOF

Output:

Hello, Ada.
Your role is: engineer.
Task count: 7.

The three lines between <<EOF and the closing EOF are sent to cat, which simply prints its input. Because the delimiter was unquoted, $name and $role were replaced with their values and the arithmetic $(( 3 + 4 )) was evaluated first. The closing EOF must sit at the very start of its line with nothing after it -- a trailing space or a leading indent (without the dash form shown later) means Bash does not recognise it and keeps reading, which is the single most common heredoc bug.


Technical Depth: Controlling What the Typist Interprets

Expanded bodies versus verbatim bodies

Quoting the delimiter is the switch between the two dictation modes. <<EOF (unquoted) expands variables and command substitutions; <<'EOF' (quoted) turns all of that off and passes every character through literally. In an unquoted body you can still protect a single dollar sign by writing a backslash in front of it.

FormDelimiter quoted?$var in bodyUse when
<<EOFnoexpandedfilling a template with values
<<'EOF'yesliteralemitting code, JSON, or docs
<<"EOF"yesliteralsame as single quotes here
#!/usr/bin/env bash
set -euo pipefail

price=42

echo "--- unquoted (expands) ---"
cat <<EOF
The price is $price dollars.
Escaped stays literal: \$price
EOF

echo "--- quoted (verbatim) ---"
cat <<'END'
The price is $price dollars.
No expansion: $(echo hi)
END

Output:

--- unquoted (expands) ---
The price is 42 dollars.
Escaped stays literal: $price
--- quoted (verbatim) ---
The price is $price dollars.
No expansion: $(echo hi)

In the first block the delimiter is bare, so $price becomes 42, while the backslash in \$price protects that one dollar sign so it prints unchanged. In the second block the delimiter is 'END' in single quotes, so nothing is touched: the literal text $price and even $(echo hi) reach the page exactly as written. The quoted form is what you reach for when the body is itself a script, a JSON document, or a lesson about the dollar sign -- anything where expansion would corrupt the content.

Trimming leading tabs with the dash form

Deeply nested heredocs look ugly when the body has to start at column one. The <<- form fixes this by stripping leading tab characters (and only tabs, never spaces) from every body line and from the closing delimiter, so you can indent the whole block to match its surroundings.

#!/usr/bin/env bash
set -euo pipefail

if true; then
	cat <<-EOF
	Report section
	  indented data stays
	EOF
fi

Output:

Report section
  indented data stays

Every line of the body above is indented with a leading tab, and the closing EOF is tabbed too; the dash form removes those tabs before the text is emitted. Notice that the two spaces in front of indented data stays survive -- the dash strips tabs only, so a body indented with spaces is passed through unchanged. This is the classic trap: convert your tabs to spaces in an editor and the dash form silently stops working while the delimiter, if it was space-indented, is no longer recognised at all.

Capturing a heredoc into a variable or a file

A heredoc is just input on a pipe, so it composes with everything that reads input. Wrap it in $( ... ) to capture the rendered text in a variable, or add a redirection to the command line to write it straight to a file with cat > file <<EOF.

#!/usr/bin/env bash
set -euo pipefail

app="billing"
port=8080
workers=4

conf=$(cat <<EOF
[service]
name = $app
port = $port
workers = $workers
EOF
)

echo "$conf"

Output:

[service]
name = billing
port = 8080
workers = 4

The $( ... ) captures everything the heredoc produced into conf, trailing newline trimmed, so the variable now holds a finished configuration block ready to write out or inspect. Swapping echo "$conf" for cat > service.conf <<EOF ... EOF would write the same rendered text directly to disk in a single step, which is the everyday way scripts scaffold config files, systemd units, and Dockerfiles.

Feeding a single line with a here-string

When you only need to hand one line to a command, the here-string <<< is lighter than a full heredoc. command <<< "$value" puts the value on standard input followed by a single newline. It pairs naturally with read for splitting a line into fields.

#!/usr/bin/env bash
set -euo pipefail

line="2026-09-24 ERROR disk-full"

read -r date level msg <<< "$line"
echo "date=$date"
echo "level=$level"
echo "msg=$msg"

grep -o 'ERROR' <<< "$line"
echo "words: $(wc -w <<< "$line")"

Output:

date=2026-09-24
level=ERROR
msg=disk-full
ERROR
words: 3

The read splits on whitespace into the three named variables, and because there are exactly three fields each lands cleanly; had there been more words, the surplus would all fold into msg. The here-string also lets grep and wc work on a value already in memory without echoing it through a pipe, which is both faster and safe from the word-splitting that an unquoted echo "$line" | can introduce.


Real World Example: Rendering a Build Report

Continuous-integration jobs love to print a tidy summary at the end: a header, a row per test suite, and a footer. Here-documents make the fixed scaffolding readable, and a loop over the data fills in the rows. The script below combines an expanded heredoc for the header, a formatted loop for the body, and a quoted heredoc for a footer that must not have its dollar sign touched.

#!/usr/bin/env bash
set -euo pipefail

title="Nightly Build"
status="passed"
rows=(
  "unit|128|0"
  "integration|54|1"
  "lint|1|0"
)

emit_header() {
  cat <<EOF
=== $title ===
overall: $status
SUITE        PASS FAIL
EOF
}

emit_row() {
  local name="$1" pass="$2" fail="$3"
  printf '%-12s %-4s %s\n' "$name" "$pass" "$fail"
}

emit_header
for r in "${rows[@]}"; do
  IFS='|' read -r name pass fail <<< "$r"
  emit_row "$name" "$pass" "$fail"
done

cat <<'EOF'
note: counts only, logs at $BUILD_URL
EOF

Output:

=== Nightly Build ===
overall: passed
SUITE        PASS FAIL
unit         128  0
integration  54   1
lint         1    0
note: counts only, logs at $BUILD_URL

The header comes from an unquoted heredoc, so $title and $status are filled in from the variables while the fixed column labels ride along as plain text. The body is not a heredoc at all: a loop walks the rows array, splits each name|pass|fail record with IFS='|' read fed by a here-string, and prints it through a printf whose %-12s %-4s widths line the columns up. The footer is a quoted heredoc, which is why the literal $BUILD_URL survives on the page instead of expanding to an empty string.

Mixing the three techniques is deliberate: heredocs are unbeatable for multi-line fixed scaffolding, but a per-row loop is clearer and safer than trying to build a growing heredoc inside the loop. Keeping the data in a simple array also means the report's content is separated from its presentation, so a change to the layout touches only the printf and the header block.

The script is honest about its limits. It does no validation of the records: a malformed row such as smoke|7 leaves fail empty and prints fail= with a blank value rather than flagging the error. The printf widths pad but never truncate, so a suite name longer than twelve characters pushes the numeric columns out of alignment instead of being cut. And the | split cannot survive a field that itself contains a pipe or a newline -- the here-string appends a newline and read stops at it -- so the format is only safe for the tightly controlled data a CI job generates, not arbitrary user input.


Common Mistakes

  1. Indenting the closing delimiter. With <<EOF the terminator must start at column one. A leading space or tab makes Bash treat it as body text and read to end of file, hanging the script.
  2. A trailing space after the delimiter word. EOF with an invisible trailing space is not the delimiter EOF; the heredoc never closes. This is maddening because it looks correct.
  3. Expecting expansion inside a quoted heredoc. Once you write <<'EOF', no $var is filled. If your template came out full of literal dollar signs, you quoted the delimiter when you did not mean to.
  1. Using spaces to indent a <<- body. The dash form strips leading tabs only. If your editor inserts spaces, the indentation is preserved in the output and the delimiter still must be tab-indented to be recognised.
  2. Forgetting that <<- does not strip indentation from the content, only from the left margin. Interior alignment inside a line survives; only the run of tabs at the start of each line is removed.
  3. Assuming a here-string adds no newline. read x <<< "value" feeds `value

`. That trailing newline is usually harmless, but code that counts bytes or compares exact content will be surprised by it.

  1. Building a command's stdin with echo piped through several stages when a heredoc would be clearer and would not mangle whitespace. A heredoc passes the body verbatim; a pipeline of echos invites word-splitting and quoting bugs.
  2. Letting an unquoted heredoc expand backticks or $(...) you did not intend. An unquoted body runs command substitution. A stray backtick in documentation text becomes a command execution; quote the delimiter for any body containing shell metacharacters you want shown literally.
  3. Redirecting a heredoc into a command that also reads other input. If a program expects its data on stdin and you also feed it a heredoc, the heredoc wins and the other source is ignored, which looks like the program silently skipping work.

Best Practices

  • Quote the delimiter when the body is a literal template. Write <<'EOF' for configuration files, code, or documentation you want reproduced exactly. Reserve the unquoted <<EOF for the moments you actually want variables filled in.
  • Choose a delimiter that cannot appear in the body. EOF is conventional, but for a body that itself mentions EOF use something distinct like END_OF_CONFIG. A delimiter that shows up mid-body ends the heredoc early.
  • Use <<- with real tabs for readable indentation. Indent the heredoc to match its surrounding block so the script reads cleanly, then let the dash form strip the tabs at runtime. Configure your editor to insert tabs, not spaces, for these regions.
  • Capture into a variable with $(cat <<EOF ... EOF) when you need the text twice. Rendering once into a variable avoids repeating the template and keeps a single source of truth for the wording.
  • Prefer a here-string over echo | for single-line input. read a b c <<< "$line" is clearer and avoids a subshell, so the variables it sets survive in the current shell.
  • Keep data separate from layout. Store rows in an array and render them in a loop rather than hand-writing every line into one giant heredoc; the layout then lives in one printf.
  • Validate fields before formatting them. If a record is split on a delimiter, check the field count so a malformed row is reported rather than silently printed with blanks.
  • Remember that printf widths pad but do not truncate. When alignment matters for untrusted names, cut the string to width with parameter expansion first, or the columns will drift.

Practice Exercises

  1. Two-form greeting. Write a script that prints the same three-line greeting twice: once from an unquoted heredoc that fills in a $user variable, and once from a quoted heredoc that shows $user literally. Confirm the two blocks differ only where the variable appears.
  2. Indented config emitter. Using <<- and real tabs, write a function nested inside an if block that emits a four-line INI section while staying visually indented in the source. Verify with cat -A that the emitted lines have no leading tabs.
  3. Here-string field parser. Read a line like name=api port=8443 tls=on by feeding it to read through a here-string, then print each field on its own line. Handle the case where a field is missing by supplying a default.
  4. Templated report with validation. Extend the build-report example so that a row with the wrong number of fields prints SKIPPED: <row> to stderr instead of a blank column, and so that a name longer than twelve characters is truncated with a trailing ~. Show the output for one good row and one bad row.