Created
August 28, 2020 11:15
-
-
Save coldfix/3ba9bdf25fe142f9c2ce11e2063d8f28 to your computer and use it in GitHub Desktop.
Simple `sh` template substitution script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env bash | |
# Substitutes shell-like templates in input files. | |
# | |
# Usage: | |
# template.sh [-x COMMAND] [-f FILE] [VAR=value]... | |
# | |
# Options: | |
# -f FILE Read template from this file [default: -] | |
# -x COMMAND Send output to this command [default: cat] | |
# | |
# Variables are also substituted from the current environment, | |
# which means that you can also pass arguments like this: | |
# | |
# export VAR1=value | |
# export VAR2=value | |
# VAR3=value VAR4=value template.sh [-f FILE] | |
filename= | |
execute=cat | |
while getopts 'f:x:h' OPTION; do | |
case $OPTION in | |
x) execute="$OPTARG" ;; | |
f) filename="$OPTARG" ;; | |
*) printf "Usage: %s: [-x command] [[-f] file] [variables ...]\n" $(basename "$0") >&2 | |
exit 2 | |
esac | |
done | |
shift $(($OPTIND - 1)) | |
if [ "xx$filename" = "xx" ]; then | |
if [ -e "$1" ]; then | |
filename="$1" | |
shift | |
else | |
filename=- | |
fi | |
fi | |
random_suffix=`dd if=/dev/urandom bs=32 count=1 2> /dev/null | hexdump -e '"%04X"'` | |
env "$@" sh <<OUTER | |
$execute <<INNER$random_suffix | |
$(cat "$filename") | |
INNER$random_suffix | |
OUTER |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment