envsubst - Linux
Overview
envsubst is a simple yet powerful command used to substitute environment variables in text files or standard input. It scans the input, replaces occurrences of ${VARIABLE}
with the corresponding environment variable value, and prints the result.
Syntax
envsubst [OPTIONS] [TEXTFILE]
Options/Flags
- -f FILE, –file=FILE: Use the specified file as input instead of standard input.
- -d DELIMITER, –delimiter=DELIMITER: Change the default delimiter from
$
to the specified character. - -u, –unset: Remove undefined environment variables from the output.
- -e, –expand: Expand nested environment variables.
- -s, –silent: Suppress error messages for undefined environment variables.
- -v, –version: Print version information and exit.
- -h, –help: Print usage information and exit.
Examples
Simple Variable Substitution:
echo "${USER}" | envsubst
# Output: testuser
Multi-Line Substitution:
cat config.txt | envsubst
# Content of config.txt:
# ${DB_HOST}
# ${DB_USER}
# ${DB_PASSWORD}
# Output:
# localhost
# dbuser
# secretpassword
Nested Variable Expansion (with -e):
envsubst -e <<EOF
DB_HOST=${HOST}
DB_USER=${USER}
EOF
# Output:
# DB_HOST=myhost
# DB_USER=testuser
Changing Delimiter (with -d):
echo "${FOO:=bar}" | envsubst -d "#"
# Output:
# bar#=bar
Common Issues
- Undefined environment variables may cause errors unless
-s
or-u
is used. - Nesting environment variables may lead to unexpected results unless
-e
is used. - envsubst can consume a lot of memory when expanding complex expressions or handling large input files.
Integration
With xargs:
find . -type f -exec envsubst {} \;
With sed:
sed -f script.sed | envsubst