I would like to use some kind of minimalistic template engine with pure bash and envsubst:
user@host:~$ env -i FOO=foo BAR="bar baz" envsubst '$FOO,$BAR' \
<<< 'Hello "$FOO" and "$BAR"!'
Hello "foo" and "bar baz"!
Above works, but only contains static variables.
Now let's assume environment variables are given dynamically, like with an associative array:
declare -A MY_ENV=([FOO]=foo [BAR]="bar baz")
Parsing the array key-value pairs only works for environment values without whitespaces (errors):
env -i \
$(for k in "${!MY_ENV[@]}"; do printf "%s=%s " $k "${MY_ENV[$k]}"; done) \
envsubst #...
Trying to wrap environment values by quotes (note '%s' instead of %s ) also errors:
env -i \
$(for k in "${!MY_ENV[@]}"; do printf "%s='%s' " $k "${MY_ENV[$k]}"; done) \
envsubst #...
Output of set -x:
Reason: :set -x shows that the argument for env becomes one giant string
+ env -i 'FOO='\''foo'\''' 'BAR='\''bar' 'baz'\''' envsubst #...
env: ‘baz'’: No such file or directory
I must have missed a shell escape lession (again...). How might I rewrite last example to work properly?