/
test_generic_variables_template.sh
executable file
·62 lines (50 loc) · 1.22 KB
/
test_generic_variables_template.sh
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#!/bin/bash
#
# using sed or envsubst to replace multiple variables in template
# blog: https://fabianlee.org/2021/05/29/bash-render-template-from-matching-bash-variables/
#
# declare variables
first="1"
animal="dog"
echo ""
echo "##########"
echo "Dollar sign templating style"
echo "##########"
# create template, heredoc without var evaluation
read -r -d '' mytemplate <<'EOF'
this is $first
the $animal goes woof
EOF
# create list of sed replacements
sedcmd=''
for var in first animal ; do
printf -v sc 's/$%s/%s/;' $var "${!var//\//\\/}"
sedcmd+="$sc"
done
sed -e "$sedcmd" <(echo "$mytemplate")
echo ""
echo "##########"
echo "Dollar sign with curly bracket style"
echo "##########"
# allow var evaluation, so escape dollar sign
read -r -d '' mytemplate <<EOF
this is \${first}
the \${animal} goes woof
EOF
# create list of sed replacements
sedcmd=''
for var in first animal ; do
printf -v sc 's/${%s}/%s/;' $var "${!var//\//\\/}"
sedcmd+="$sc"
done
sed -e "$sedcmd" <(echo "$mytemplate")
echo ""
echo "##########"
echo "Using envsubst"
echo "##########"
export first
export animal
# only substitute listed variables
echo "$mytemplate" | envsubst '$first $animal'
# substitute all env variables
#echo "$mytemplate" | envsubst