Skip to main content
Heredocs let you include multi-line text or commands directly within a Bash script, avoiding repetitive echo statements and manual editing. They’re invaluable for generating configuration files, embedding SQL queries, or executing batches of commands over SSH—especially in non-interactive environments where editors like Vim or Nano aren’t available.
A Heredoc sends an entire block of text as input to a command. This keeps your scripts clean and reduces the risk of accidental overwrites when using > vs. >>.
The image illustrates a process flow for "Heredocs," showing data from a file (file.txt) being processed with variables, commands, and scripts to produce a result.

Why Choose Heredocs Over Multiple echo Commands

Using individual echo lines quickly becomes error-prone as your script grows:
If you mistakenly use > instead of >>, you can overwrite your file. Heredocs treat the block as a single unit of input, eliminating this risk.

Basic Heredoc Syntax

Feed a block of text into any command—here, cat—using the <<DELIM operator:
Output:
To write directly to a file, redirect the command’s output:
Tips for smooth usage:
  • The closing delimiter must match exactly (case-sensitive) and have no leading spaces.
  • Common delimiters include EOF, EOM, or a custom token of your choice.
If you mistype the closing token, the shell will continue to prompt for input until you either provide the correct delimiter or cancel with Ctrl+C.

Common Use Cases for Heredocs


Quick Checklist: Heredoc Benefits

The image is a slide titled "Heredocs" with checkmarks next to "One-liner," "Include large blocks of text," and "Complex scripts."
  • One-liner for simple operations
  • Embed large blocks of text without quotes
  • Support complex scripting scenarios

Remote Command Execution via SSH

You can run multiple commands on a remote host in one go. First, check your remote directory:
Next, supply commands through a Heredoc:
Verify the result:
Expected output:

Here Strings for Single-Line Input

When you need to pass a single line of text into a command, a Here String (<<<) is more concise:
Here Strings avoid quoting headaches and extra redirection symbols for small data payloads.
Feel free to explore these resources to deepen your understanding of shell scripting techniques and automation workflows.

Watch Video

Practice Lab