Last active
August 29, 2015 14:21
-
-
Save brandon15811/ffe3e7ed943ed348426d to your computer and use it in GitHub Desktop.
Bash templating. {{VARIABLE}} renders to the env variable $VARIABLE
This file contains hidden or 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 | |
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