Skip to content

Instantly share code, notes, and snippets.

@onnimonni
Forked from pebo/env-susbst.sh
Last active August 3, 2016 20:28
Show Gist options
  • Save onnimonni/8e7420457af31d6521b92aaae5497295 to your computer and use it in GitHub Desktop.
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
#!/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