-
-
Save onnimonni/8e7420457af31d6521b92aaae5497295 to your computer and use it in GitHub Desktop.
envsubst like substitution; only replacing $VAR or ${VAR} if they have a value in in env
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# envsubst like substitution; only replacing ${VAR} if they exists | |
# based on http://mywiki.wooledge.org/TemplateFiles | |
# source: https://gist.github.com/pebo/c30d9b4819e908a305244874c916a4dc | |
while read -r; do | |
while [[ $REPLY =~ \$(\{([a-zA-Z_][a-zA-Z_0-9]*)\})(.*) ]]; do | |
if [[ -n ${!BASH_REMATCH[2]} ]]; then | |
printf %s "${REPLY%"$BASH_REMATCH"}${!BASH_REMATCH[2]}" | |
else | |
printf %s "${REPLY%"$BASH_REMATCH"}\$${BASH_REMATCH[2]}" | |
fi | |
else # found ${var} | |
if [[ -n ${!BASH_REMATCH[3]} ]]; then | |
printf %s "${REPLY%"$BASH_REMATCH"}${!BASH_REMATCH[3]}" | |
else | |
printf %s "${REPLY%"$BASH_REMATCH"}\${${BASH_REMATCH[3]}}" | |
fi | |
fi | |
REPLY=${BASH_REMATCH[4]} | |
done | |
printf "%s\n" "$REPLY" | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment