Skip to content

Instantly share code, notes, and snippets.

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