Bash HereDoc Tutorial With Examples


If you're a Linux or Unix user, you're probably familiar with Bash, command-line shell that's commonly used on these systems. Bash has a lot of powerful features that can make working on command line much more efficient, and one of those features is called a "HereDoc." In this tutorial, we'll explain what a HereDoc is, how it works, and give you some examples of how you can use it in your Bash scripts.

What is a HereDoc?

A HereDoc, short for "Here Document," is a way to include a block of text within a Bash script. This block of text can contain anything you want, including commands, variables, and other special characters. HereDocs are useful because they allow you to include large blocks of text without having to worry about escaping special characters or dealing with complicated quoting rules.

Here's an example of a HereDoc in action −

cat << EOF
This is a HereDoc example.
It can include multiple lines of text.
EOF

In this example, we're using "cat" command to output a block of text to terminal. "<< EOF" syntax tells Bash to start a HereDoc block, and "EOF" at end tells Bash where block ends. Anything between those two markers is included in HereDoc.

The HereDoc block can contain any text you want, including variables, commands, and other special characters. Here's an example that demonstrates how to use a HereDoc to store a SQL query in a variable −

query=$(cat << EOF
   SELECT *
   FROM users
   WHERE username='john.doe';
   EOF
)

echo "$query"

In this example, we're using a HereDoc to store a SQL query in "query" variable. We're then using "echo" command to output contents of variable to terminal. This can be a very useful technique when you need to store large blocks of text in a script.

HereDoc Syntax

The basic syntax for a HereDoc is as follows −

command << EOF
text
EOF

In this syntax, "command" is command that will receive HereDoc as input, and "text" is block of text that will be included in HereDoc. "EOF" marker tells Bash where HereDoc ends.

The HereDoc syntax is very flexible and can be used in a variety of ways. Here are some examples −

You can use a HereDoc to provide input to a command, like this −

command << EOF
input
EOF

You can use a HereDoc to assign a block of text to a variable, like this −

variable=$(cat << EOF
   text
   EOF
)

You can use a HereDoc to create a file with a block of text, like this −

cat << EOF > file.txt
text
EOF

You can use a HereDoc to append a block of text to a file, like this −

cat << EOF >> file.txt
text
EOF

HereDoc Examples

Let's take a look at some real-world examples of how HereDocs can be used in Bash scripts.

Example 1: HereDoc to Create a Configuration File

Suppose you're writing a script that needs to read settings from a configuration file. Instead of creating file manually, you can use a HereDoc to generate file from within your script. Here's an example −

cat << EOF > config.ini
[server]
host = example.com
port = 80

[database]


name = mydatabase
user = myuser
password = mypassword
EOF

In this example, we're using a HereDoc to generate a configuration file called "config.ini". file contains several sections, including a "server" section and a "database" section. Each section contains several key-value pairs that define settings for script.

By using a HereDoc to generate configuration file, we can ensure that file is always generated correctly and that it contains all necessary settings.

Example 2: HereDoc to Run a SQL Script

Suppose you have a SQL script that you need to run on a remote server. Instead of copying script to server and running it manually, you can use a HereDoc to run script remotely. Here's an example −

ssh user@example.com << EOF
mysql -u myuser -p mypassword < script.sql
EOF

In this example, we're using a HereDoc to run a SQL script called "script.sql" on a remote server. We're using "ssh" command to connect to server, and "<< EOF" syntax to start a HereDoc block.

The HereDoc block contains a single command, "mysql -u myuser -p mypassword < script.sql", which runs SQL script on remote server. By using a HereDoc to run script remotely, we can avoid need to copy script to server manually.

Example 3: HereDoc to Generate HTML Output

Suppose you're writing a script that needs to generate HTML output. Instead of concatenating strings and tags manually, you can use a HereDoc to generate HTML code. Here's an example −

cat << EOF > index.html

<!DOCTYPE html>
<html>
<head>
   <title>My Website</title>
</head>
<body>
   <h1>Welcome to my website</h1>
   <p>This is some sample text.</p>
</body>
</html>
EOF

In this example, we're using a HereDoc to generate an HTML file called "index.html". file contains a basic HTML structure, including a title, a header, and some sample text. By using a HereDoc to generate HTML code, we can ensure that code is always generated correctly and that it contains all necessary tags.

Additional tips and best practices for HereDocs

Use Descriptive Markers

When defining HereDoc block, use a descriptive marker instead of just "EOF". For example, if you're defining a SQL query, you could use "<< SQL" as marker. This makes code more readable and helps avoid confusion.

Use Single Quotes

When defining HereDoc block, it's best to use single quotes around marker. This prevents Bash from interpreting any variables or special characters in block.

Use Indentation

When defining HereDoc block, it's a good idea to use indentation to make code more readable. This is especially useful when block contains multiple levels of indentation.

Use "-r" option

When reading input from a HereDoc, it's a good idea to use "-r" option with read command. This prevents backslashes from being interpreted as escape characters.

Avoid Using Tabs

When defining HereDoc block, avoid using tabs for indentation. This can cause issues with some commands, especially those that expect input to be formatted a certain way.

Use Variables in HereDocs

You can use variables in HereDocs just like you would in any other part of your Bash script. This can be a powerful technique for generating dynamic content.

Use HereDocs with other Bash Features

HereDocs can be used in combination with other Bash features, such as loops, conditionals, and functions. This can make your scripts even more powerful and flexible.

By following these tips and best practices, you can use HereDocs effectively in your Bash scripts and take advantage of their many benefits. Whether you're generating configuration files, running remote scripts, or generating HTML output, HereDocs can help make your Bash scripts more efficient and effective.

Conclusion

In this tutorial, we've explained what a HereDoc is and how it works in Bash. We've also given you some examples of how you can use HereDocs in your Bash scripts, including generating configuration files, running SQL scripts remotely, and generating HTML output.

HereDocs are a powerful feature of Bash that can help you write more efficient and effective scripts. By using HereDocs, you can include large blocks of text in your scripts without having to worry about escaping special characters or dealing with complicated quoting rules. So if you're a Bash user, be sure to give HereDocs a try!

Updated on: 31-Mar-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements