I have a project that needs to render a template. I want to ensure in advance that all variables in the template are not empty.
I was able to extract a template with a single row of data containing only one variable by a script like:
- template file: tmpl_single.tmpl
{
"var1": "${VARIABLE_1}",
"var2": "${VARIABLE_2}",
"var3": "${VARIABLE_3}"
}
- shell script file: generate.sh
#!/bin/bash
DIR_BASE="$(cd "$(dirname "$0")" && pwd)"
render_2_file() {
template_file=$1
out_file=$2
set +u
for env in $(sed -n 's/^[^#].*${\(.*\)}.*/\1/p' $template_file); do
# debug
echo "$env : $(eval echo \$${env})"
if [ -z "$(eval echo \$${env})" ]; then
echo "environment variable '${env}' not set"
missing=true
fi
done
if [ "${missing}" ]; then
echo 'Please check the above variable'
exit 1
fi
eval "cat << EOF
$(cat ${template_file})
EOF" >"$out_file"
set -u
}
main(){
# debug generate
# VARIABLE_1=var1_val
# VARIABLE_2=var1_val
# VARIABLE_3=var1_val
# single var in one line
TMPL_PATH=$DIR_BASE/tmpl_single.tmpl
OUT_FILE=$DIR_BASE/tmpl_single.json
# multi var in one line
# TMPL_PATH=$DIR_BASE/tmpl_multi.tmpl
# OUT_FILE=$DIR_BASE/tmpl_multi.json
echo "check path = $OUT_FILE"
if [ ! -f "$OUT_FILE" ]; then
echo "not found, generating"
render_2_file "$TMPL_PATH" "$OUT_FILE"
if [ $? = 0 ]; then
echo "generate successfully"
fi
else
echo "out file existed, no need to generate"
fi
}
main "$@"
The output result is as follows, it can detect the case of one variable in a single line, at this time, the output is wrong and the target file is not generated
stdout:
not found, generating
VARIABLE_1 :
environment variable 'VARIABLE_1' not set
VARIABLE_2 :
environment variable 'VARIABLE_2' not set
VARIABLE_3 :
environment variable 'VARIABLE_3' not set
Please check the above variable
However, if a single line in the template file contains multiple variables, only the last variable in the line can be extracted.
- template file: tmpl_multi.tmpl
{
"var12": "test1_${VARIABLE_1}:test2_${VARIABLE_2}",
"var3": "test3_${VARIABLE_3}"
}
- stdout:
not found, generating
VARIABLE_2 :
environment variable 'VARIABLE_2' not set
VARIABLE_3 :
environment variable 'VARIABLE_3' not set
Please check the above variable
It can be seen from the above output that variable VARIABLE_1
is not extracted.
Please tell me how to extract multiple variables wrapped by ${}
in a row of data. Looking forward to your reply.