Skip to content

Instantly share code, notes, and snippets.

@dlip
Created May 11, 2014 02:30
Show Gist options
  • Save dlip/2051ef4136e42e2b5e1c to your computer and use it in GitHub Desktop.
Save dlip/2051ef4136e42e2b5e1c to your computer and use it in GitHub Desktop.
Replaces variables in a template using shell script
#!/bin/bash
if [ $# -eq 0 ]
then
echo "Templater"
echo "Copies templates from one folder to another."
echo "Only replaces variables that exist in the environment"
echo "Usage: templater IN_FOLDER OUT_FOLDER"
exit 1
fi
if [ ! "$(ls -A $1)" ]; then
# No files, nothing to do
exit 0
fi
ENV_VARS=$(env | sed 's/=.*//')
#Fix ordering to make longer variable name get used first
ENV_VARS=$(echo "$ENV_VARS" | awk '{ print length, $0 }' | sort -n -r | cut -d" " -f2-)
FILES=$1/*
# Loop over files in folder
for f in $FILES; do
# Grab text to variable
text=$(<$f)
# Loop over environment variables
while read -r env_var; do
val="${!env_var}"
#escape value for sed
val=$(echo "$val" | sed 's/[\/&]/\\&/g')
string="\$$env_var"
text=$(echo "$text" | sed "s/$string/$val/g")
done <<< "$ENV_VARS"
# Output files
echo "$text" > "$2/$(basename $f)"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment