DEV Community

Cover image for Using Bash HereDoc
Sanskriti Harmukh for Vultr

Posted on with Aashish Chaurasiya Originally published at docs.vultr.com

Using Bash HereDoc

Bash HereDoc, also known as Here Document, is an input redirection feature that allows you to enter multiline inputs to a command or a script. HereDoc works with cat, tee, variables, and special characters in Bash, making it useful when executing large blocks of code. This guide explains how to use Bash HereDoc to redirect multiline inputs to commands such as cat. By the end, you'll be able to build config files, disable chunks of script code, pass multiline input over SSH, and feed HereDoc input into functions.


1. The Bash HereDoc Syntax

A HereDoc uses the following syntax in Bash.

[COMMAND] << 'DELIMITER'
  # Contents
DELIMITER
Enter fullscreen mode Exit fullscreen mode

In the above command:

  • COMMAND: Specifies the command to redirect the HereDoc input to.
  • <<: Defines the special redirection operator.
  • DELIMITER: Marks the beginning and the end of a HereDoc. The value can be any string, but EOF and END are commonly used with HereDoc. The beginning and closing delimiters must match to terminate the HereDoc correctly.
  • contents: Specifies the HereDoc text or input to pass to the command.

The following HereDoc options modify the type of input contents passed to a command for execution.

  • <<: Reads the input content until a closing delimiter is detected. All variables and special characters are substituted to the shell before passing the HereDoc to the command.
  • <<-: Enables indenting input and removing or ignoring all leading tab characters.
  • << "DELIMITER": Treats all HereDoc contents as a single string to interpret variables and escape characters in the input.
  • << 'DELIMITER': Prevents variable expansion and interpretation of escape characters in the input.

2. Use Here String

A Here string is similar to HereDoc in Bash, but it does not require a delimiter token to pass a string or data as input to a command. A Here string uses the <<< redirection operator to pass contents to a command without manual input. You can pass variables, special characters, and plain strings similar to any command using the following syntax.

COMMAND <<< # Contents
Enter fullscreen mode Exit fullscreen mode

1. Create a new Here string that prints your current user:

$ cat <<< "Your current user is: $(whoami)"
Enter fullscreen mode Exit fullscreen mode

Output:

Your current user is: root
Enter fullscreen mode Exit fullscreen mode

2. Escape special characters, such as @, #, !, $, and ^, using single quotes in a Here string to prevent the system from interpreting the characters:

$ cat <<< 'Hello World! Special characters like @,$,% are not interpreted with single quotes ON: !,}'
Enter fullscreen mode Exit fullscreen mode

Output:

Hello World! Special characters like @,$,% are not interpreted with single quotes ON: !,}
Enter fullscreen mode Exit fullscreen mode

3. Pass contents to a variable using a Here string:

$ read var1 <<< "Hello World! This Works"
Enter fullscreen mode Exit fullscreen mode

4. Print the variable to view the contents:

$ echo $var1
Enter fullscreen mode Exit fullscreen mode

Output:

Hello World! This Works
Enter fullscreen mode Exit fullscreen mode

3. Bash HereDoc Examples

Follow the steps below to use Bash HereDoc with multiple commands.

1. Create a HereDoc that prints the working directory, the active user, and the system date:

$ cat << END
  Your current user is: $(whoami)
  Working directory: $PWD
  System date: $(date)
  END
Enter fullscreen mode Exit fullscreen mode

Output:

Your current user is: user
Working directory: /home/user
System date: Wed Oct 09 09:58:14 PM UTC 2024
Enter fullscreen mode Exit fullscreen mode

2. Create a new var1 variable that stores the values from a HereDoc:

$ var1=$(cat <<'EOF'
  Line 1.
  This is the second line.
  Just the third line.
  EOF
  )
Enter fullscreen mode Exit fullscreen mode

3. Print the variable:

$ echo $var1
Enter fullscreen mode Exit fullscreen mode

Output:

Line 1. This is the second line. Just the third line.
Enter fullscreen mode Exit fullscreen mode

4. Redirect the HereDoc command output to create a new file, such as doc.txt:

$ cat << EOF > doc.txt
  Hello World!
  EOF
Enter fullscreen mode Exit fullscreen mode

5. Redirect the output from a HereDoc command and append it to a file:

$ cat << EOF >> doc.txt
  This works!
  EOF
Enter fullscreen mode Exit fullscreen mode

6. Modify the output of a HereDoc command using sed and redirect the output to a file:

$ cat <<'EOF' | sed 's/Hello/Hi/g; s/Works/Functions Well/g' > newfile.txt
  Hello World!
  This Works!
  EOF
Enter fullscreen mode Exit fullscreen mode

Create Configuration Files with Bash HereDoc

You can use Bash HereDoc to write configuration files instead of manually creating the files. This is important in scripts that read specific contents from a configuration file to run specific tasks. You can use a HereDoc to create a file and remove it after performing the task. Follow the steps below to use HereDoc to create new configuration files.

1. Create a new configuration.ini file using HereDoc:

$ cat <<EOF > configuration.ini
  [Database]
  host=localhost
  port=3306
  username=admin
  password=admin123

  [Server]
  host=127.0.0.1
  port=8000
  EOF
Enter fullscreen mode Exit fullscreen mode

2. View the contents of the configuration file using the cat command:

$ cat configuration.ini
Enter fullscreen mode Exit fullscreen mode

Output:

[Database]
host=localhost
port=3306
username=admin
password=admin123

[Server]
host=0.0.0.0
port=8000
Enter fullscreen mode Exit fullscreen mode

Disable Bash Script Contents with HereDoc

You can use comments in Bash to disable specific blocks of code in a script by adding the # symbol at the beginning of every line to create a comment. HereDoc disables script contents more efficiently using the dummy command : that does not return any value. Follow the steps below to use Bash HereDoc to disable multiple lines of code in a script.

1. Create a new heredoc.sh script using a text editor like vim:

$ vim heredoc.sh
Enter fullscreen mode Exit fullscreen mode

2. Add the following contents to the heredoc.sh file:

#!/bin/bash

echo "Hello World! This Works!"

: <<'EOF'
echo "Hello User! This is disabled!"
EOF

echo "This runs"
Enter fullscreen mode Exit fullscreen mode

Save the file.

In the above script, all contents between the HereDoc EOF delimiters are disabled and do not run in the script.

3. Run the script using Bash:

$ bash heredoc.sh
Enter fullscreen mode Exit fullscreen mode

Output:

Hello World! This Works!
This runs
Enter fullscreen mode Exit fullscreen mode

Use HereDoc with SSH

You can use HereDoc with SSH to run multiple commands on a remote system without an interactive session. SSH works as the command and forwards the HereDoc input that runs when the remote connection establishes.

$ ssh -T user@host.com cat << EOF
  Your current user is: $(whoami)
  Working directory: $PWD
  System date: $(date)
  EOF
Enter fullscreen mode Exit fullscreen mode

In the above SSH command, the -T option disables the interactive shell to input the HereDoc that prints the working directory, the active user, and the remote system's date. Your output should look like the one below when successful.

Your current user is: user
Working directory: /home/user
System date: Wed Oct 09 09:58:14 PM UTC 2024
Enter fullscreen mode Exit fullscreen mode

4. Use Bash HereDoc with Functions

HereDoc works with functions to process multiline input in Bash scripts. Calling the function name works as the command and the HereDoc redirects the input contents to the function. For example:

1. Create a new heredoc-func.sh script:

$ vim heredoc-func.sh
Enter fullscreen mode Exit fullscreen mode

2. Add the following contents to the heredoc-func.sh file:

#!/bin/bash

my_function() {
    local var="$1"
    echo "$var"
}

my_function "$(cat << 'EOF'
Hello World! This Works!
EOF
)"
Enter fullscreen mode Exit fullscreen mode

Save the file.

In the above script, HereDoc writes multiple messages while calling the function and the echo command prints the input values within the function to display the output.

3. Run the script using Bash:

$ bash heredoc-func.sh
Enter fullscreen mode Exit fullscreen mode

Output:

Hello World! This Works!
Enter fullscreen mode Exit fullscreen mode

5. Use HereDoc with Custom Delimiters

The HereDoc EOF and END delimiters are commonly used in Bash. You can use other delimiters to make files and code more readable. A delimiter can consist of any custom string such as txt for creating text files, abc, or xyz for any other files based on your logic. Follow the steps below to use different delimiters with HereDoc in Bash to write files.

1. Create a new var1 variable and set a custom HereDoc delimiter, such as sql:

$ var1=$(cat << 'sql'
  SELECT * FROM users;
  sql
  )
Enter fullscreen mode Exit fullscreen mode

2. Print the variable:

$ echo "$var1"
Enter fullscreen mode Exit fullscreen mode

Output:

SELECT * FROM users;
Enter fullscreen mode Exit fullscreen mode

3. Create a new config.ini configuration file from a HereDoc and set cfg as the delimiter:

$ cat << 'cfg' > config.ini
  [Database]
  host=localhost
  port=3306
  username=admin
  password=admin123

  [Server]
  host=0.0.0.0
  port=8000
  cfg
Enter fullscreen mode Exit fullscreen mode

4. Use HereDoc with a php delimiter to create a new PHP application file:

$ cat << 'php' > index.php
  echo "Hello World! PHP Works!";
  php
Enter fullscreen mode Exit fullscreen mode

Next Steps

  • Use HereDoc to generate boilerplate config files (nginx, systemd units, .env files) as part of provisioning scripts.
  • Swap <<EOF for <<'EOF' whenever you need literal text without variable expansion.
  • Combine HereDoc with SSH to run a batch of remote commands in a single non-interactive connection.
  • Use the : <<'EOF' ... EOF pattern to quickly comment out large blocks of a script during debugging.

For the full guide with additional tips, visit the original article on Vultr Docs.

Top comments (0)