Skip to content

Instantly share code, notes, and snippets.

@dmotylev
Last active August 29, 2015 14:11
Show Gist options
  • Save dmotylev/d582263085b659797a65 to your computer and use it in GitHub Desktop.
Save dmotylev/d582263085b659797a65 to your computer and use it in GitHub Desktop.
simple bash template engine
#!/usr/bin/env bash
if ! [[ ${BASH_VERSINFO[0]} -ge 4 && ${BASH_VERSINFO[1]} -ge 2 ]]; then
echo "$(basename $0): bash version >= 4.2 required"
exit 1
fi
#
# expands {{varname}} to varvalue
#
expand_variables ()
{
local line="$(cat; echo -n a)"
local end_offset=${#line}
while [[ "${line:0:$end_offset}" =~ (.*)(\{\{([a-zA-Z_][a-zA-Z_0-9]*)\}\})(.*) ]] ; do
local pre="${BASH_REMATCH[1]}"
local post="${BASH_REMATCH[4]}${line:$end_offset:${#line}}"
local varname="${BASH_REMATCH[3]}"
eval 'local varval="$'$varname'"'
line="$pre$varval$post"
end_offset=${#pre}
done
echo -n "${line:0:-1}"
}
source deploy.rc.defaults
[ -f deploy.rc.local ] && source deploy.rc.local
expand_variables
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment