How to Use Bash HereDoc

By Raman Kumar

Updated on Dec 12, 2024

In this tutorial, we'll learn how to use Bash HereDoc.

Bash HereDoc, short for "Here Document," is a powerful feature for redirecting input into a script or command. It allows you to create multi-line strings and redirect them to commands or files without having to escape special characters or manually append lines. This tutorial provides an in-depth exploration of HereDoc, ranging from basic usage to advanced applications, using real-world examples.

What Is Bash HereDoc?

A HereDoc is a form of redirection that lets you embed multi-line strings directly within a Bash script or command. It is defined by the syntax << followed by a delimiter. The content until the closing delimiter is treated as input.

Prerequisites

Before you begin using the sftp command, ensure the following:

  • A KVM VPS or dedicated server with any Linux distro installed.
  • SSH Access: You must have SSH access to the remote system.

How to Use Bash HereDoc

Basic Syntax

command <<DELIMITER
content
DELIMITER
  • command: The command that will process the content (e.g., cat, tee).
  • DELIMITER: A string to indicate the start and end of the HereDoc. Commonly, uppercase words like EOF are used.
  • content: The multi-line string to be passed as input.

Example: Creating a Sample Configuration File

Suppose you want to create an Apache HTTP server configuration file using Bash HereDoc. Here's how you can do it:

#!/bin/bash

# Define the configuration file path
config_file="/etc/httpd/conf/httpd.conf"

# Create the configuration file using HereDoc
sudo tee "$config_file" > /dev/null <<EOF
# Apache HTTP Server Configuration

ServerName localhost
Listen 80

<VirtualHost *:80>
    DocumentRoot "/var/www/html"
    ErrorLog "/var/log/httpd/error.log"
    CustomLog "/var/log/httpd/access.log" common
</VirtualHost>
EOF

echo "Configuration file created at $config_file"

Explanation:

1. sudo tee "$config_file" > /dev/null: 

  • tee writes the HereDoc content to the specified file.
  • > /dev/null suppresses the standard output to avoid cluttering the terminal.

2. The content between <<EOF and EOF is the configuration text.
3. The DocumentRoot, ErrorLog, and other parameters are standard Apache configurations.

The script ends by notifying the user about the created file.

Using Variables Inside HereDoc

You can use variables in HereDoc by ensuring the delimiter is unquoted:

#!/bin/bash

user="JohnDoe"
server="example.com"

cat <<EOF
Hello, $user!
Welcome to $server.
EOF

Output:

Hello, JohnDoe!
Welcome to example.com.

However, if you quote the delimiter, variables are treated as literal strings:

cat <<"EOF"
Hello, $user!
EOF

Output:

Hello, $user!

Redirecting HereDoc to a File

Use the > or >> operators to redirect HereDoc content to a file:

cat <<EOF > example.txt
This is the first line.
This is the second line.
EOF

This overwrites example.txt with the HereDoc content. Use >> to append instead.

Advanced Usage: Embedding Scripts

HereDoc can embed entire scripts within a larger script:

#!/bin/bash

# Generate a temporary script
cat <<'EOF' > temp_script.sh
#!/bin/bash
echo "This is a temporary script."
EOF

# Make the script executable
chmod +x temp_script.sh

# Execute the script
./temp_script.sh

# Cleanup
rm -f temp_script.sh

Key Points:

The delimiter is quoted ('EOF') to prevent expansion of variables or commands inside the HereDoc.

Advanced Usage: Passing HereDoc to Commands

HereDoc can be piped into other commands for processing. For instance:

awk <<EOF '{ print toupper($0) }'
hello world
this is heredoc
EOF

Output:

HELLO WORLD
THIS IS HEREDOC

Using HereDoc with SQL Queries

HereDoc is widely used to execute multi-line SQL queries:

#!/bin/bash

db_user="root"
db_pass="password"
db_name="testdb"

mysql -u "$db_user" -p"$db_pass" "$db_name" <<EOF
CREATE TABLE IF NOT EXISTS users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(50) NOT NULL,
    email VARCHAR(100) NOT NULL UNIQUE
);
INSERT INTO users (name, email) VALUES ('Alice', 'alice@example.com');
EOF

This script creates a users table and inserts a record into a MySQL database.

Tips and Best Practices

1. Choose a Unique Delimiter: Avoid conflicts with the content by selecting an uncommon delimiter.

cat <<MYDELIM
Uncommon delimiters reduce errors.
MYDELIM

2. Escape Sequences: Use quoted delimiters to include special characters like $, \, or ` literally.

3. Error Handling: Always check the success of commands that process HereDoc content.

if cat <<EOF > config.txt
Configuration Data
EOF
then
    echo "File created successfully."
else
    echo "Failed to create file."
fi

4. Indentation: To improve readability, use <<-DELIMITER to ignore leading tabs (not spaces) in HereDoc content.

cat <<-EOF
    Indented content here.
EOF

Conclusion

Bash HereDoc is a versatile feature for managing multi-line input in scripts. Whether you're creating configuration files, embedding scripts, or executing complex commands, HereDoc simplifies your workflow while keeping your scripts clean and readable. Mastering HereDoc can significantly enhance your Bash scripting skills, making your scripts more efficient and professional.