Here Document Template Substitution
Generate a config file from a here document template with variable expansion and command substitution.
Code
#!/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.yamlHow 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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.