Bash templating

From campisano.org
Jump to navigation Jump to search

Apply script

#!/usr/bin/env bash
#
# NAME      template_apply.sh
# VERSION   1.0.1
# REQUIRED  envsubst
#

set -o errexit -o nounset -o pipefail

if test "$#" -ne 2; then
    echo "Usage: `basename $0` <template-file> <output-file>" >&2
    exit 1
fi

TEMPLATE_FILE=$1
OUTPUT_FILE=$2

VARS=$(sed -e '/#/Q' ${TEMPLATE_FILE})
TEMPLATE=$(sed -e '1,/### End template/d' ${TEMPLATE_FILE})

for V in $VARS
do
    VARNAME=`echo $V | cut -b 2-`
    read -r -p ${VARNAME}= $VARNAME
    export $VARNAME
done

echo "$TEMPLATE" | envsubst "${VARS}" > ${OUTPUT_FILE}


References