Envsubst
envsubst
, short for environment substitution, makes it easy to substitute environment variables in a text file. This is a simple way to template files.
Usage
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.
#!/bin/bash
## If no argument is passed, FirstName will be set to 'stranger'
FirstName="${1:-stranger}"
echo "Hello there, $FirstName" | envsubst