← Back to Bash Course | Chapter 13: Advanced Scripting | Lesson 6 of 7

Heredoc Templating (Generating a Config File from Variables)

You can build a text file whose contents change based on variables in your script, by writing the desired layout once as a template and letting Bash fill in the blanks.

Generating a Config File from Variables

Because the heredoc delimiter here is unquoted, every $variable inside the block is expanded to its current value before being written out, effectively turning the heredoc into a template.

Example: Generating a Config File from Variables

bash
#!/bin/bash
host="db.example.com"
port=5432
user="app_user"

cat > db_config.ini <<EOF
[database]
host=$host
port=$port
user=$user
EOF

cat db_config.ini
rm -f db_config.ini

Including Command Substitution in a Template

Because expansion happens the same way it does in double-quoted strings, $(command) inside an unquoted heredoc runs the command and inserts its output, useful for stamping a generated file with a timestamp or hostname.

Example: Including Command Substitution in a Template

bash
#!/bin/bash
version="1.2.0"

cat > release_notes.txt <<EOF
Release: $version
Generated year: $(date +%Y)
EOF

cat release_notes.txt
rm -f release_notes.txt

Validating Required Variables Before Templating

Checking that every variable the template needs is actually set beforehand avoids silently generating a config file with blank or missing values, which can be a hard-to-diagnose bug later.

Example: Validating Required Variables Before Templating

bash
#!/bin/bash
host="localhost"
port=""

if [[ -z $host || -z $port ]]; then
    echo "missing required template variable(s), skipping generation" >&2
else
    cat > out.ini <<EOF
host=$host
port=$port
EOF
fi
echo "validation check complete"
Common Mistakes
  1. Quoting the heredoc delimiter (<<EOF) when you actually wanted variable substitution, which produces literal $var text instead of the expanded value.
  2. Forgetting that command substitution and arithmetic expansion also happen inside an unquoted heredoc, not just simple variable expansion.
  3. Not validating that all required variables are set before generating a config file, which can silently produce a broken file with empty values.
Chapter Summary
  • An unquoted heredoc delimiter allows variables, command substitution, and arithmetic expansion inside the block.
  • Redirecting a heredoc into a file with > filename is a simple, readable way to generate config files from a template.
  • Combine heredoc templating with set -u (or explicit checks) so a missing variable causes a clear error rather than an empty gap in the generated file.
  • Nested double quotes inside an unquoted heredoc don't need escaping the way they would inside a quoted string.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.