Templating and Substitution
Fill templates and generate files using parameter expansion and simple tools.
Parameter expansion patterns
name=${name:-guest} # default (no assignment)
name=${name:=guest} # assign default
path=${path%/} # trim shortest suffix
path=${path%%/*} # trim longest suffix pattern
msg=${msg/foo/bar} # replace first
msg=${msg//foo/bar} # replace all
Here-doc templates
cat > config.ini <<EOF
[app]
name=${APP_NAME}
port=${PORT:-3000}
EOF
Use single-quoted delimiter (<<'EOF') to disable expansion when you want a literal template.
envsubst
export APP_NAME=myapp PORT=3000
envsubst < config.tmpl > config
Substitute ${VAR} placeholders from the environment.
printf and small DSLs
printf '[%s] %s\n' "$level" "$msg" >> app.log
`
Safety and quoting
- Always quote expansions to avoid word splitting/globbing
- Validate inputs before substitution to avoid injection into config files
Summary
- Use parameter expansion and here-docs for simple templating
- Reach for
envsubstfor environment-driven configs