0
0
Bash Scriptingscripting~3 mins

Why Here documents (<<EOF) in Bash Scripting? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how a simple marker can save you from tedious typing and messy files!

The Scenario

Imagine you need to create a multi-line text file or send a block of text to a command in your terminal. Doing this manually means typing each line one by one, or creating a separate file and then referencing it. This feels like writing a letter by hand every time you want to send a message.

The Problem

Manually typing or managing multiple lines is slow and prone to mistakes. You might forget a line, add extra spaces, or lose track of where the text starts and ends. Also, juggling separate files for input clutters your workspace and breaks your flow.

The Solution

Here documents let you write all your multi-line text directly inside your script or command, clearly marking where it starts and ends. This keeps everything neat, reduces errors, and saves time by avoiding extra files or repeated typing.

Before vs After
Before
echo "Line 1" > file.txt
echo "Line 2" >> file.txt
echo "Line 3" >> file.txt
After
cat <<EOF > file.txt
Line 1
Line 2
Line 3
EOF
What It Enables

It makes handling blocks of text in scripts simple, clean, and error-free, unlocking smoother automation and clearer code.

Real Life Example

When setting up a server, you often need to create configuration files with many lines. Using here documents, you can write the entire config inside your setup script, so the server is ready with one command.

Key Takeaways

Manual multi-line input is slow and error-prone.

Here documents let you embed multi-line text directly in scripts.

This simplifies automation and keeps your code clean.