epcim
6/14/2016 - 5:23 AM

Shell variable substitution from within a file.

Shell variable substitution from within a file.

##
# Just found the amazing builtin 'mapfile', perfect
# for substitution variable inside a file by its values.
##

mateus@mateus:/tmp$ cat input.txt 
a = $a
b = $b
mateus@mateus:/tmp$ echo a=$a, b=$b
a=1, b=2
mateus@mateus:/tmp$ function subst() { eval echo -E "$2"; }
mateus@mateus:/tmp$ mapfile -c 1 -C subst < input.txt 
a = 1
b = 2


##
# Simpler solution
##

mateus@mateus:/tmp$ EOF=EOF_$RANDOM; eval echo "\"$(cat <<$EOF
$(<input.txt)
$EOF
)\""
a = 1
b = 2