LinuxCommandLibrary

envsubst

Substitute environment variables in a template file

TLDR

Replace environment variables in stdin and output to stdout

$ echo '[$HOME]' | envsubst
copy

Replace environment variables in an input file and output to stdout
$ envsubst < [path/to/input_file]
copy

Replace environment variables in an input file and output to a file
$ envsubst < [path/to/input_file] > [path/to/output_file]
copy

Replace environment variables in an input file from a space-separated list
$ envsubst < [path/to/input_file] '[$USER $SHELL $HOME]'
copy

SYNOPSIS

envsubst [OPTION]... [SHELL-FORMAT]...

PARAMETERS

-D name, --dollar name
    substitute ${name*} as $name* without command substitution

-i, --ignore-environment
    ignore environment variables with empty values

-v, --variables
    output names of variables that are substituted (one per line)

-h, --help
    display this help and exit

-V, --version
    display version information and exit

DESCRIPTION

envsubst is a utility from the GNU gettext package that substitutes environment variable values into shell-style format strings. It processes input from specified files or stdin, replacing references like $VAR or ${VAR} with corresponding environment values, and outputs the result to stdout.

This tool excels in dynamic configuration generation, such as templating files for containers (e.g., Docker) or scripts where runtime environment variables customize settings. For example, a template config.ini with placeholders can be transformed into a populated version before application startup.

By default, all environment variables are considered; unset variables leave their references intact. It handles multiple input files sequentially without altering originals. Key options control behavior: ignore empty vars, list substituted vars, or define custom dollar-prefix substitutions to avoid command execution pitfalls.

Unlike full shell eval, it avoids executing commands or nested expansions, ensuring safe, predictable substitution focused on env vars only.

CAVEATS

Does not support nested vars, command substitution ($(cmd)), or backticks. Unset vars unchanged. No input file modification; use redirection for that. Limited to env vars only.

EXAMPLE

echo 'User: $USER, Home: ${HOME}' | envsubst
Outputs: User: youruser, Home: /home/youruser

envsubst < config.tmpl > config.prod

EXIT STATUS

0 on success, 1 on error (e.g., invalid option, read/write fail)

HISTORY

Introduced in GNU gettext 0.12 (2001) for i18n tasks; gained popularity for config templating in DevOps.

SEE ALSO

env(1), sed(1), awk(1)

Copied to clipboard