brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: envsubst fills shell variables into a template file

Shell
~/tips/tip-shell-envsubst-template

envsubst < site.conf.tpl > site.conf

Turn a config template with $VARIABLES into a real file without sed.

When you need a config file with a few values filled in, I’d reach for envsubst before writing a pile of sed commands. It comes with GNU gettext and replaces $VAR and ${VAR} with values from the environment.

The variables have to be exported, because envsubst is a separate program and only sees the environment:

export SITE=example.com PORT=8080
envsubst < site.conf.tpl > site.conf

With a template line like server_name $SITE; you get server_name example.com; in the output.

The catch is that it replaces every variable it finds, also the ones you meant to keep. An nginx template full of $host and $uri turns into empty strings, and a variable you forgot to export also becomes empty without any warning. Pass the list of names you want replaced and it leaves everything else alone:

envsubst '$SITE $PORT' < site.conf.tpl > site.conf

Keep that list in single quotes, otherwise your shell expands it before envsubst sees it. On Debian and Ubuntu it lives in the gettext-base package, and the official nginx images use it for their own templates folder.

Further reading: GNU gettext: envsubst Invocation

More Shell tips zmv -n '(*).log' '$1.txt' zoxide query -ls project f=$(mktemp --suffix=.json) shopt globskipdots echo $EPOCHSECONDS All Shell tips (78) All topics

Link