Cybersecurity Updates & Tools

Bash Heredoc Explained: Complete Guide With Examples

Introduction

Bash heredoc, also called here document, is a useful feature in Bash scripting that allows you to pass multiple lines of text to a command. It is commonly used when you want to write multi-line text into a file, create configuration files, send input to commands, or generate scripts automatically.

If you are learning Bash scripting, heredoc is an important concept because it makes scripts cleaner and easier to read. Instead of using many echo commands, you can use one heredoc block to handle multiple lines.

What Is Heredoc In Bash?

A heredoc allows you to redirect multiple lines of input to a command.

Basic syntax:

command << EOFline 1line 2line 3EOF

Here, EOF is called a delimiter. It marks the beginning and end of the heredoc block. You can use another word instead of EOF, but the starting and ending words must match.

Basic Bash Heredoc Example

Create a new Bash script:

nano heredoc-example.sh

Add the following code:

#!/bin/bashcat << EOFWelcome to Bash scripting.This is a heredoc example.You can print multiple lines easily.EOF

Save and run the script:

chmod +x heredoc-example.sh./heredoc-example.sh

Output:

Welcome to Bash scripting.This is a heredoc example.You can print multiple lines easily.

Write Multiple Lines To A File Using Heredoc

Heredoc is very useful for writing text into a file.

#!/bin/bashcat > message.txt << EOFHello,This file was created using Bash heredoc.Bash scripting is useful for Linux automation.EOF

Run the script and check the file:

cat message.txt

This creates a file named message.txt with multiple lines of content.

Use Variables Inside Heredoc

By default, Bash expands variables inside heredoc.

#!/bin/bashname="Kali Linux"topic="Bash Scripting"cat << EOFWebsite Topic: $topicOperating System: $nameCurrent User: $(whoami)EOF

This is useful when generating reports, logs, or configuration files dynamically.

Prevent Variable Expansion In Heredoc

If you do not want variables to expand, quote the delimiter.

#!/bin/bashcat << 'EOF'This will print $USER as plain text.Command output like $(date) will not run.EOF

This is helpful when creating script templates or documentation files.

Cybersecurity Example: Create A Simple Report

#!/bin/bashcat > security-report.txt << EOFSecurity ReportGenerated On: $(date)Current User: $(whoami)Hostname: $(hostname)Open Ports:$(ss -tuln)EOF

This script creates a basic security report with system and network information.

Conclusion

Bash heredoc is a simple and powerful way to handle multi-line input in Bash scripts. You can use it to print text, create files, generate reports, write configuration files, and build automation scripts.

For beginners, learning heredoc helps make Bash scripts cleaner and easier to manage. It is especially useful in Linux administration, cybersecurity scripting, reporting, and automation tasks