Skip to content

Instantly share code, notes, and snippets.

@kshaa
Created June 1, 2020 13:05
Show Gist options
  • Select an option

  • Save kshaa/0adaa9fe0383826ef1b96c7622a4562a to your computer and use it in GitHub Desktop.

Select an option

Save kshaa/0adaa9fe0383826ef1b96c7622a4562a to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
function help() {
echo "Usage $0 [TEMPLATE] [RENDER]"
echo "Replaces all instances of '\$TPL_*' in TEMPLATE and write to RENDER"
echo "If RENDER not provided, will print to stdout"
}
template="$1"
if [ -z "$template" ]
then
echo "Error: No template file provided"
echo
help
exit 1
fi
render="$2"
if [ -z "$render" ]
then
echo "Warn: No render file provided, printing to stdout"
echo
fi
# Prepare environment variables
export ENV_VARS_PREFIX="TPL_" ## Prefix for substitutable variables
export ENV_VARS_REGEX="^${ENV_VARS_PREFIX}.*=" ## Regex that matches variables with a given prefix
## Variables = all variables | find variables matching given regex | add dollar signs in beginning | replace newlines with spaces
## Dollar signs are required because envsubst requires variables in the following format `envsubst "$VAR1 $VAR2 $VAR3"`
export BASE_VARS="$(env | grep -o ${ENV_VARS_REGEX} | sed 's/^/$/g' | sed 's/=//g' | tr '\n' ' ')"
export EXTRA_VARS="${EXTRA_VARS:=""}"
export ENV_VARS="${BASE_VARS} ${EXTRA_VARS}"
# Print environment variables
# echo "Base substitution variables = ${BASE_VARS}"
# echo "Extra substitution variables = ${EXTRA_VARS}"
echo "All substitution variables = { ${ENV_VARS} }"
if [ ! -e "$template" ]
then
echo "Error: Template file doesn't exist"
exit 1
fi
# Render asset
if [ -z "$render" ]
then
echo "Rendering $template"
echo
envsubst "${ENV_VARS}" < $template
else
echo "Rendering $template into $render"
echo
envsubst "${ENV_VARS}" < $template > $render
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment