Skip to content

Instantly share code, notes, and snippets.

@brandon15811
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brandon15811/ffe3e7ed943ed348426d to your computer and use it in GitHub Desktop.
Save brandon15811/ffe3e7ed943ed348426d to your computer and use it in GitHub Desktop.
Bash templating. {{VARIABLE}} renders to the env variable $VARIABLE
#!/bin/bash
if [ -z "$1" ]; then
echo "No file specified"
exit 1
fi
if [ ! -f "$1" ]; then
echo "File doesn't exist"
exit 1
fi
#First character of a variable name must be a letter or an underscore
#Rest of variable can only contain letters, numbers, and underscores
for var in $(grep -oE '\{\{([A-Za-z_][A-Za-z0-9_]+)\}\}' "$1"); do
#Remove { and } from variable name
strippedVar=$(echo $var | tr -d '{}')
#If variable is not set, ${var+x} evaluates to null: http://stackoverflow.com/a/13864829
#${!var} explanation: http://stackoverflow.com/a/16553351
if [ -z ${!strippedVar+x} ]; then
echo "${strippedVar} not set, exiting"
exit 1
fi
#Escape special characters in value for use in sed
escapedValue=$(echo ${!strippedVar} | sed -e 's/[\/&]/\\&/g')
sed -i "s/${var}/${escapedValue}/" "$1"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment