Course contentsShow
← Linux
Lesson 125 of 1,8192. Deep Dive into Bash ScriptingFree lesson

Heredoc and Herestring Orchestration

Embed dynamic templates and multiline input streams within shell logic.

In this lesson, you will learn how to feed multiline blocks of text and dynamic variables directly into commands without needing external configuration files.

The Power of Heredocs

A Heredoc (short for "here-document") allows you to pipe a block of text into a command as if it were a physical file. By using the << operator, you define a custom delimiter (like EOF), and everything you type until that delimiter appears is treated as the input stream. This is perfect for generating configuration files or dynamic emails within your script.

# Generating a config file dynamically
cat << EOF > my_config.conf
# Dynamic Configuration
User=admin
Date=$(date +%Y-%m-%d)
EOF

Notice how $(date) is evaluated inside the Heredoc. This makes it a powerful template engine for your scripts. If you want to prevent variable expansion, wrap the delimiter in quotes (e.g., << 'EOF').

The Precision of Herestrings

While a Heredoc is for blocks of text, a Herestring is for compact, single-line input. Using the <<< operator, you can pass a string directly to a command's standard input. It is the cleanest way to avoid using echo piped into another command (the "useless use of cat" anti-pattern).

Compare these two approaches:

  1. The Pipe approach: echo "Hello" | grep "H"
  2. The Herestring approach: grep "H" <<< "Hello"

The second version is more efficient because it avoids spawning a subshell for the echo command.

When to Orchestrate Them

You should use Heredocs when you need to maintain readability for multi-line logic, such as embedding SQL queries into database CLI tools or writing entire scripts to remote servers over SSH. Use Herestrings whenever you have a single variable or constant that needs to be processed by a command that expects input from standard streams. Both techniques ensure your data stays tightly coupled with your logic, reducing reliance on temporary files.

Key Takeaway: Heredocs manage complex, multiline data templates, while Herestrings provide a lightweight, subshell-free method to pass single-line inputs into standard streams.