Per the man page:
envsubst [OPTION] [SHELL-FORMAT]
If a SHELL-FORMAT is given, only those environment variables that
are referenced in SHELL-FORMAT are substituted; otherwise all
environment variables references occurring in standard input are
substituted.
Where SHELL-FORMAT strings are "strings with references to shell variables in the form $variable
or ${variable}
[...] The variable names must consist solely of alphanumeric or underscore ASCII characters, not start with a digit and be nonempty; otherwise such a variable reference is ignored.".
Note that the format ${VAR:-default}
is not supported. I mentioned HERE some alternatives that support it along with other features.
Anyway, back to gettext
envsubst
:
So, one has to pass the respective variables names to envsubst
in a shell format string (obviously, they need to be escaped/quoted so as to be passed literally to envsubst
). Example:
input file e.g. infile
:
VAR1=${VAR1}
VAR2=${VAR2}
VAR3=${VAR3}
and some values like
export VAR1="one" VAR2="two" VAR3="three"
then running
envsubst '${VAR1} ${VAR3}' <infile
or
envsubst '${VAR1},${VAR3}' <infile
or
envsubst '${VAR1}
${VAR3}' <infile
outputs
VAR1=one
VAR2=${VAR2}
VAR3=three
Or, if you prefer backslash:
envsubst \$VAR1,\$VAR2 <infile
produces
VAR1=one
VAR2=two
VAR3=${VAR3}
To avoid leakage of the custom-set variables into the executing shell's environment, instead of exporting these variables, some shells such as Bash allow prefixing the command with variable assignments. The values assigned in this way will only be used for the command's execution, and don't affect the shell environment afterwards:
export VAR1="one" VAR2="two" VAR3="three"
...
VAR1="number 1" VAR3="numero 3" envsubst '${VAR1} ${VAR3}' <infile
output:
VAR1=number 1
VAR2=${VAR2}
VAR3=numero 3
echo "VAR1=${VAR1}"
echo "VAR2=${VAR2}"
echo "VAR3=${VAR3}"
output shows that the original environment was preserved:
VAR1=one
VAR2=two
VAR3=three
envsubst "$(printf '${%s} ' ${!PREFIX*})" < infile
– Sam Liddicott Jan 22 '19 at 15:13SUBST_VARS
then:envsubst "$(printf '${%s} ' $SUBST_VARS)" < infile
– Sam Liddicott Jan 22 '19 at 15:15--help
output. – Mr. Lance E Sloan Jul 13 '20 at 18:45envsubst "$(compgen -e | awk '$0="${"$0"}"')" < infile
. – Nishant Oct 17 '20 at 09:51-v
or--variables
flag to output the variables given in SHELL-FORMAT (to verify that your syntax is correct): e.g.envsubst -v '${VAR1} $VAR2 NOVAR'
. – Dario Seidl Nov 23 '20 at 14:10VAR1=one VAR2=two VAR3=three
– Matt Alexander Mar 01 '21 at 09:55envsubst '$$DOCKER_NGINX_LOCAL_IP' < infile
– Snake_py Jul 06 '22 at 13:01