/
envtemplate
executable file
·73 lines (64 loc) · 1.83 KB
/
envtemplate
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
63
64
65
66
67
68
69
70
71
72
73
#!/bin/sh
#
# Simple script that replaces mustached variables in any file with matching
# environment variables (if available).
#
# Templates:
#
# Templates can be any file. Just place a {{MUSTACHED}} version of the
# environment variable and it will be replaced with the environment variable's
# value when the template is rendered (see below).
#
# Rendering the Template:
#
# envtemplate render --in some-template.txt --out rendered-file.txt
#
# Usually the script works with pre-set environment variables but if you want
# you can pass environment variables like so:
#
# MY_VAR=myval envtemplate render --in some-template.txt --out rendered-file.txt
#
# Print the usage info.
usage() {
echo "usage: env-template render --in some-template --out rendered-file | [-h --help]"
}
# Render the template and output the result.
render() {
# Get all keys out of the template.
keys=$(awk '{while (match($0, /\{\{[^\}]*\}\}/)) {pattern = substr($0, (RSTART + 2), (RLENGTH - 4)); printf pattern" "; $0 = substr($0, RSTART + RLENGTH);}}' $IN)
# Start with the input file.
cp $IN $OUT
# Loop through all found keys.
set -- $keys
while [ -n "$1" ]; do
key=$1
value=$(eval "echo \$$key")
sed -i.bak "s/{{$key}}/${value}/g" $OUT
shift
done
}
# Get the arguments
COMMAND=$1
shift
# Only the 'render' command is supported at this point.
if [ "$COMMAND" != "render" ]; then
usage
exit 1
fi
while [ "$1" != "" ]; do
case $1 in
-i | --in ) shift
IN=$1
;;
-o | --out ) shift
OUT=$1
;;
-h | --help ) usage
exit
;;
* ) usage
exit 1
esac
shift
done
$COMMAND