
envsubst: Substituting Environment Variables in Shell Strings
What is envsubst
- A small helper from GNU gettext that substitutes environment variables in shell format strings.
- It recognizes variables in the forms ${var} and $var.
When to use envsubst
- You need to render templates or config files with dynamic values from the current environment.
- You want a simple, POSIX-friendly tool without a full templating engine.
Basic usage (stdin to stdout)
- This reads text from stdin, replaces variables, and prints to stdout.
- Example: substitute $HOME inside a string you echo:
echo 'Your home is ${HOME}' | envsubst
Notes:
- Single quotes prevent shell expansion before envsubst runs; you can also rely on envsubst to replace placeholders.
- If a variable is not defined, envsubst leaves the placeholder as-is (no error).
Using a file as input (stdout)
- envsubst can read from a file and print the result to stdout.
envsubst < path/to/input_file
Using a file as input (save to a file)
- Redirect the output to a file to save the substitutions.
envsubst < path/to/input_file > path/to/output_file
Substituting a selective set of variables
- You can tell envsubst which variables to substitute by passing a quoted list of variables in the ${var} or $var form.
- The list must be space-separated and enclosed in quotes.
# Substitute only USER, SHELL, and HOME inside input_file
envsubst '${USER} ${SHELL} ${HOME}' < path/to/input_file
Common pitfalls and tips
- Undefined variables: If a variable in your template is not defined, its placeholder remains unchanged. Define defaults or export variables as needed.
- Literal dollar signs: If you want a literal $ in the output, escape it as $$ in the input or ensure you don’t have a conflicting template.
- Quoting: Be mindful of how your shell expands variables before feeding text to envsubst. Using echo or cat can influence results depending on quotes.
- Performance: For large templates, streaming with stdin is convenient; for many substitutions, a small templating tool might be clearer.
Compared to alternatives
- envsubst is great for lightweight substitution but lacks conditional logic or loops found in full templating engines.
- For complex templates, consider tools like envsubst in combination with other utilities or a templating language that supports guards and iterations.
Example summary
- Replace environment variables in a string:
echo 'Hello, ${USER}. Your shell is $SHELL.' | envsubst
- Substitute specific variables inside a file and save to another file:
envsubst '${USER} ${HOME}' < templates/config.tpl > configs/config.conf