public
Last active

Shell variable substitution from within a file.

  • Download Gist
var-file-subst.sh
Shell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
##
# 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$ eval echo "\"$(cat <<EOF_$RANDOM
$(<input.txt)
EOF_$RANDOM
)\""
a = 1
b = 2

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.