Here Document Template Substitution

Generate a config file from a here document template with variable expansion and command substitution.

BashConfig Management

Code

bashsnippet
16 lines
#!/usr/bin/env bash
set -euo pipefail

APP_NAME="myapp"
PORT="${1:-8080}"
HOSTNAME=$(hostname)

cat > config.yaml <<EOF
app:
  name: ${APP_NAME}
  port: ${PORT}
  host: ${HOSTNAME}
  generated: $(date -u +%Y-%m-%dT%H:%M:%SZ)
EOF

cat config.yaml

How it works

Strict mode (set -euo pipefail) makes failures loud — an unset variable or a failing pipeline stage aborts the script instead of being swallowed.

The work is delegated to cat, chained so each stage’s output feeds the next.

The script leans on parameter expansion 4 times, using forms like ${var:-default} so defaults, trimming, and casing happen inside the shell with no external tool.

Key statements worth quoting

HOSTNAME=$(hostname)
cat > config.yaml <<EOF
generated: $(date -u +%Y-%m-%dT%H:%M:%SZ)

Interactive Tools for This Topic

FAQ

Does the script stop on the first error?
Yes — `set -euo pipefail` aborts on the first failing command, treats unset variables as errors, and fails the whole pipeline if any stage fails. Nothing continues half-broken.
Which external commands does the script rely on?
`cat` must be available on the PATH environment variable; everything else is shell built-in syntax.