← Back to Bash Course | Chapter 8: Input/Output & Redirection | Lesson 10 of 13

Here-Documents (<<EOF)

A here-document lets you embed a multi-line block of text directly inside a script and feed it to a command as if it were a file.

A Basic Here-Document

<<DELIM starts a here-document; everything until a line containing exactly DELIM becomes the stdin of the preceding command. This is a clean way to embed multi-line text without a pile of echo calls.

Example: A Basic Here-Document

bash
#!/bin/bash
cat <<EOF
Line one
Line two
Line three
EOF

Variable Expansion Inside a Here-Document

By default, variables and command substitutions inside a here-document are expanded just like in double quotes. Quoting the delimiter, e.g. <<EOF, disables that expansion and treats the block as literal text.

Example: Variable Expansion Inside a Here-Document

bash
#!/bin/bash
name="Ada"
cat <<EOF
Hello, $name!
Today is a scripted day.
EOF

echo "---"
cat <<'EOF'
This $name will NOT be expanded.
EOF

Generating a File with a Here-Document

Redirecting a here-document into a file is a common way to generate configuration files or templates from within a script.

Example: Generating a File with a Here-Document

bash
#!/bin/bash
cat > config.txt <<EOF
host=localhost
port=8080
EOF
cat config.txt
rm -f config.txt

Indented Here-Documents with <<-

<<-DELIM strips leading tab characters (not spaces) from each line, including the closing delimiter, so you can indent a here-document to match the surrounding code inside a function.

Warning: <<- strips leading tabs only, not spaces, so mixing spaces and tabs will break the trick.

Example: Indented Here-Documents with <<-

bash
#!/bin/bash
show_message() {
	cat <<-EOF
	This line was indented with a tab.
	So was this closing delimiter.
	EOF
}
show_message
Common Mistakes
  1. Forgetting that the closing delimiter (like EOF) must be on its own line with no leading whitespace unless you use <<-.
  2. Not realizing variables and command substitutions inside a here-document are expanded by default, which can be surprising if you wanted literal text.
  3. Mismatching the opening and closing delimiter names, which makes bash keep reading the rest of the script as part of the here-document.
Chapter Summary
  • <<DELIM ... DELIM feeds everything in between as stdin to a command.
  • Quoting the delimiter (<<EOF) disables variable expansion inside the block.
  • <<-EOF allows the closing delimiter to be indented with tabs, useful inside indented functions.
  • Here-documents are commonly used to generate config files or multi-line messages.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.