Skip to content

Instantly share code, notes, and snippets.

@magnetikonline
Last active November 6, 2018 11:54
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save magnetikonline/e2b34287c143b2e01f6eec91b45e4a8d to your computer and use it in GitHub Desktop.
Save magnetikonline/e2b34287c143b2e01f6eec91b45e4a8d to your computer and use it in GitHub Desktop.
Bash file templating function.

File templating with Bash

Performs the application of given key/value pairs to a source template, with generated results written to an output file.

Functions applyTemplate accepts three arguments:

  • Source template file.
  • Target output file generated.
  • List of key/value pairs as an array.

Example

With the given source template:

Hello, %%COMPUTER%%. Do you read me, %%COMPUTER%%?
Affirmative, %%SPACE_MAN%%. I read you.
Open the pod bay doors, %%COMPUTER%%.
I'm sorry, %%SPACE_MAN%%. I'm afraid I can't do that.

And by calling applyTemplate like so:

applyList=(
	"COMPUTER=HAL" \
	"SPACE_MAN=Dave"
)

applyTemplate \
	"./template.txt" \
	"./output.txt" \
	applyList

We end up with a result in output.txt of:

Hello, HAL. Do you read me, HAL?
Affirmative, Dave. I read you.
Open the pod bay doors, HAL.
I'm sorry, Dave. I'm afraid I can't do that.
#!/bin/bash -e
function applyTemplate {
# nameref name/value array, create temp file of template
local -n nameValueList=$3
local tempFile=$(mktemp)
cp "$1" "$tempFile"
# apply each value given
local nameValueItem
for nameValueItem in "${nameValueList[@]}"; do
# split name/value as captures
if [[ ! $nameValueItem =~ ^([A-Z][A-Z_]+[A-Z])=(.+)$ ]]; then
continue
fi
# escape value for sed call
local injectValue=$(echo "${BASH_REMATCH[2]}" | sed "s/[\/&]/\\\&/g")
# apply value to template temp file
sed \
--in-place \
"s/%%${BASH_REMATCH[1]}%%/$injectValue/g" \
"$tempFile"
done
# move temp file to target
mv "$tempFile" "$2"
chmod --reference "$1" "$2"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment