Bash: render template from matching bash variables

If you can conform to a bit of naming convention, one way to easily render template files in Bash is to have the template and bash variables names match.  Then you can either use sed or envsubst to do the substitution.

For example, here are two variables being defined and then placeholders embedded into the template.

# define and export variables
export first="1"
export animal="dog"

# define template string, heredoc without var evaluation
read -r -d '' mytemplate <<'EOF'
this is $first
the $animal goes woof
EOF

You can use use the envsubst utility to easily render the template.

$ echo "$mytemplate" | envsubst '$first $animal'
this is 1
the dog goes woof

Or you can generate, then apply a list of sed substitutions.

# create list of sed replacements
sedcmd=''
for var in first animal ; do
  printf -v sc 's/$%s/%s/;' $var "${!var//\//\\/}"
  sedcmd+="$sc"
done

# do all template substitutions
sed -e "$sedcmd" <(echo "$mytemplate")

See my test_generic_variables_template.sh on github for a full example.

 

REFERENCES

sed reference

howtobuildsoftware.com, replace bash variables in template file

stackoverflow, heredoc without variable evaluation

gnu.org, process substitution allowing process to be file descriptor

NOTES

variables do not have to be exported, they can also be set directly

$ echo "$mytemplate" | first=1 animal=dog envsubst '$first $animal'