Here Documents with <<

Su Suriya Ravichandran Updated 06 Dec 2026
8 min read ·Lesson 63 of 205

A here document (often written as "heredoc") lets you put several lines of text directly inside a script or command line and give that text to a command as its standard input. There is no separate file to create and nothing to read from disk: the text is part of the script itself. Here documents are used for multi-line messages, generated configuration files, SQL scripts, and any case where a block of text belongs with the commands that use it.

Understanding the Concept

So far, standard input has come from the keyboard, from a file (<), or from another command (|). A here document adds a fourth source: lines written inline, right after the command, up to a marker line that you choose. The shell collects those lines, treats them as the content of a temporary input, and attaches it to the command's standard input.

Syntax

command <<DELIMITER
line 1
line 2
DELIMITER

The operator << is followed by a delimiter word. The delimiter can be any word you like; EOF is a common choice, and END or TEXT work just as well. The shell then reads lines until it finds a line that contains only the delimiter, with nothing before it and nothing after it. The delimiter line itself is not part of the text.

Basic Example

cat <<EOF
Hello
World
EOF

Output:

Hello
World

Understanding the Example

The command is cat, which copies its standard input to its standard output. The here document supplied two lines, Hello and World, as that input. The word EOF on its own line told the shell where the text ended, and cat printed what it received.

The delimiter is just a marker. If the text itself needs a line that says EOF, choose a different delimiter. A line is the end marker only when it contains exactly the delimiter:

cat <<EOF
line with EOF inside
 EOF with leading space is not the end
EOF

Output:

line with EOF inside
 EOF with leading space is not the end

Both of the first two lines contain the letters EOF, but neither is exactly the delimiter, so they were treated as text.

Expansion Inside a Here Document

When the delimiter is written without quotes, the shell processes the body of the here document much as it would inside double quotes. It performs variable expansion, command substitution and arithmetic expansion:

name="Ana"
cat <<EOF
Hi $name, today is $(echo Friday).
Sum: $((2+3))
Literal dollar: \$HOME
EOF

Output:

Hi Ana, today is Friday.
Sum: 5
Literal dollar: $HOME

Each of the first two lines used a different expansion: $name became Ana, $(echo Friday) was replaced by the output of the command, and $((2+3)) was calculated. A backslash before the dollar sign, as in \$HOME, prevents the expansion and prints the dollar sign literally. Inside an unquoted here document, a backslash also protects the backslash itself and the backtick:

cat <<EOF
cost: \$5 and backslash: \\ and backtick: \`
EOF

Output:

cost: $5 and backslash: \ and backtick: `

A backslash at the end of a line joins it with the next line, as in a script:

cat <<EOF
one \
two
EOF

Output:

one two

Turning Expansion Off with a Quoted Delimiter

If any part of the delimiter word is quoted, the shell does not expand anything in the body. Everything is passed through exactly as written:

cat <<'EOF'
Hi $name, $(date) $((2+3)) \n
EOF

Output:

Hi $name, $(date) $((2+3)) \n

Single quotes around the delimiter ('EOF') are the most common form, but double quotes ("EOF") and a backslash before the delimiter (\EOF) also turn expansion off:

cat <<\EOF
Hi $name
EOF

Output:

Hi $name

With a quoted delimiter, the line continuation shown above stops working too, and the backslash and the line break are kept:

cat <<'EOF'
one \
two
EOF

Output:

one \
two

Quote the delimiter whenever the text contains many dollar signs, for example when writing another shell script or an awk program into a file.

Removing Leading Tabs with <<-

Indenting the lines of a here document keeps a script readable inside functions and loops, but the indentation becomes part of the text. The variant <<- removes leading tab characters from every body line and from the delimiter line:

f() {
	cat <<-EOF
	indented text
	EOF
}
f

Output:

indented text

The body line and the closing EOF were both indented with a tab, and the output contains no leading whitespace. Only tab characters are removed. Spaces are not, which matters because many editors insert spaces when you press Tab. The next test uses four spaces, and the delimiter line is not recognized:

cat <<-EOF
    four spaces
    EOF
EOF

Output:

    four spaces
    EOF

The line EOF was kept as text, because it still began with spaces, and only the last EOF ended the here document.

Writing a Here Document to a File

A here document supplies standard input, so it combines with output redirection. This is the usual way to create a small file from a script:

cat > config.txt <<EOF
host=localhost
port=8080
EOF
cat config.txt

Output:

host=localhost
port=8080

Use >> to add lines to an existing file:

cat >> config.txt <<EOF
debug=true
EOF
cat config.txt

Output:

host=localhost
port=8080
debug=true

Both redirections can appear on the same command line, in any order. The shell reads the here document body from the lines that follow the command.

Using a Here Document with Other Commands

Any command that reads standard input can receive a here document, with any arguments it needs:

sort <<EOF
pear
apple
fig
EOF

Output:

apple
fig
pear
grep -c a <<EOF
banana
cherry
apple
EOF

Output:

2

The count is 2 because only banana and apple contain the letter a.

A function reads standard input too, so a here document can feed a function that processes lines:

show() { while IFS= read -r l; do echo "> $l"; done; }
show <<EOF
a
b
EOF

Output:

> a
> b

Storing a Here Document in a Variable

Combine a here document with command substitution to store a multi-line string:

msg=$(cat <<EOF
line1
line2
EOF
)
printf '%s\n' "$msg"

Output:

line1
line2

Another approach uses read with an empty delimiter, which makes it read until the end of its input. The option -d '' stops read from treating the newline as the end:

read -r -d '' text <<'EOF'
first
second
EOF
printf '[%s]\n' "$text"

Output:

[first
second]

The command read -d '' returns a non-zero status because it reaches the end of input before finding a delimiter. A script with set -e active should expect that, and a later lesson on strict mode (119) covers the effect.

Running a Block of Commands Through Another Shell

Because standard input can be a program, a here document can hold a script that another interpreter runs. With a quoted delimiter, the body is passed unchanged, so the variables are evaluated by the receiving shell and not by yours:

bash -s <<'EOF'
echo "running in child bash: $0"
x=5; echo $((x*2))
EOF

Output:

running in child bash: bash
10

The option -s tells Bash to read the commands from standard input. This pattern is how scripts send a block of commands to a remote machine; a later lesson on SSH automation (179) uses it.

Two Here Documents on One Line

A command line can start more than one here document. The bodies follow in the order the operators appeared:

cat <<A; cat <<B
first doc
A
second doc
B

Output:

first doc
second doc

What Happens When the Delimiter Is Missing

If the input ends before the delimiter appears, Bash uses everything up to the end of the script as the body, and prints a warning:

cat <<EOF
no end here

Output when run as a script file named missing.sh:

missing.sh: line 2: warning: here-document at line 1 delimited by end-of-file (wanted `EOF')
no end here

The message shows the line number where the here document began and the delimiter that was expected. A misspelled delimiter or an extra space before it are the usual causes.

A Note on How Bash Delivers the Text

The shell provides the here document to the command as an ordinary standard input. In the Bash 5.2 sandbox used for these tests, the descriptor was a pipe for a small body:

ls -l /proc/self/fd/0 <<EOF | awk '{print $NF}' | sed 's/[0-9]\+/N/'
x
EOF

Output:

pipe:[N]

Older Bash versions used a temporary file instead. The command cannot tell the difference, and you should not rely on either form. The behavior described in the earlier sections also holds in Dash, the shell behind sh on Debian and Ubuntu:

dash -c 'cat <<EOF
hi $((1+1))
EOF'

Output:

hi 2

Here documents with << and <<- are part of the POSIX shell standard, so they work in scripts that start with #!/bin/sh. The next lesson covers here strings, a Bash-specific shorthand for a single line of input.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Here Documents with << and get answers drawn from it.

Signed-in readers only.