Last active
August 3, 2016 20:28
-
-
Save pebo/c30d9b4819e908a305244874c916a4dc 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 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 or ${VAR} if they exists | |
# based on http://mywiki.wooledge.org/TemplateFiles | |
while read -r; do | |
while [[ $REPLY =~ \$(([a-zA-Z_][a-zA-Z_0-9]*)|\{([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