Start Coding

Topics

Bash Here Documents (Heredocs)

Here documents, often called "heredocs," are a powerful feature in Bash scripting. They provide a convenient way to include multiline strings or input in your scripts.

What is a Here Document?

A here document is a type of redirection that allows you to pass multiple lines of input to a command. It's particularly useful when you need to include large blocks of text or complex input in your scripts.

Basic Syntax

The basic syntax for a here document is as follows:

command << DELIMITER
Your multiline content goes here
More lines of content
DELIMITER

The DELIMITER can be any word you choose, but it's common to use EOF (End Of File) or EOT (End Of Text).

Examples

1. Creating a File with Multiple Lines

cat << EOF > myfile.txt
This is the first line.
Here's another line.
And one more for good measure.
EOF

This command creates a file named myfile.txt with the specified content.

2. Passing Multiline Input to a Command

grep 'important' << EOT
This line is not important.
This line is very important!
Another unimportant line.
EOT

This example uses grep to search for the word "important" in the provided text.

Advanced Usage

Suppressing Tab Expansion

By default, Bash performs tab expansion in here documents. To prevent this, you can use <<- instead of <<:

cat <<- EOF
        This line will have leading tabs removed.
            This one too.
EOF

Variable Expansion

Here documents allow variable expansion by default. To disable it, quote the delimiter:

name="John"
cat << 'EOF'
Hello, $name!
EOF

This will output Hello, $name! literally, without expanding the variable.

Best Practices

  • Choose a unique delimiter to avoid conflicts with your content.
  • Use meaningful delimiters like EOF, EOT, or CONTENT for clarity.
  • Indent your here document content for better readability in scripts.
  • Be cautious with variable expansion in here documents to avoid unintended consequences.

Related Concepts

To further enhance your Bash scripting skills, consider exploring these related topics:

Here documents are a versatile tool in Bash scripting. They simplify the process of working with multiline text and can significantly improve the readability and maintainability of your scripts.