1

I have to introduce some templating over text configuration files (yaml, xml, json) that already contain bash-like syntax variables. I need to preserve existing bash-like variables untouched but substitute my ones. List is dynamic, variables should come from environment. Something like simple processor taking "$${MY_VAR}}" pattern but ignoring $MY_VAR. Preferably pure Bash or as small number of tooling required as possible.

Pattern could be $$(VAR) or anything that can be easily separated from ${VAR} and $VAR. The key limitation - it is intended for a docker container startup procedure injecting environment variables into provided service configuration templates and this way building this configuration. So something like Java or even Perl processing is not an option.

Does anybody have a simple approach?

I was using the following bash processing for such variable substitution where original files had no variables. But now I need something one step smarter.

# process input file ($1) placing output into ($2) with shell variables substitution.
process_file() {
set -e
eval "cat <<EOF
$(<$1)
EOF
" | cat > $2
}
Roman Nikitchenko
  • 12,800
  • 7
  • 74
  • 110

1 Answers1

1

Obvious clean solution that is too complex for Docker file because of number of packages needed:

perl -p -i -e 's/\$\{\{([^}]+)\}\}/defined $ENV{$1} ? $ENV{$1} : $&/eg' < test.json

This filters out ${{VAR}}, even better - only set ones.

Roman Nikitchenko
  • 12,800
  • 7
  • 74
  • 110