From Leo's Notes
Last edited on 30 December 2021, at 01:32.

envsubst, short for environment substitution, makes it easy to substitute environment variables in a text file. This is a simple way to template files.


envsubst can replace variables in the form of ${VAR} and $VAR with the value defined as an environment variable. The template file is piped to envsubst.

A simple example with one variable:

$ export FirstName=leo
$ echo "hello ${FirstName}" | envsubst
hello leo

To save the generated output, simply redirect it to a file.

$ export FirstName=leo
$ echo "hello ${FirstName}" | envsubst > hello.txt

While envsubst isn't capable of supporting more advanced shell features such as ${VAR:-default_value}, you can still make use of it inside a shell script.


## If no argument is passed, FirstName will be set to 'stranger'
echo "Hello there, $FirstName" | envsubst