Skip to content

Instantly share code, notes, and snippets.

@vi
Last active April 22, 2016 07:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save vi/6b73639a275f3b22261f to your computer and use it in GitHub Desktop.
Save vi/6b73639a275f3b22261f to your computer and use it in GitHub Desktop.
Simplify setting multiple environment variables using templates
#!/bin/bash
ENVTEMPLATER_SEPARATOR='%'
if [[ -z "$1" || $1 = "--help" ]]; then
echo >&2 "Usage: T_template1=substitution1 ... T_templateN=substitutionN envtemplater arg%...%template ... arg%...%template -- command [arguments]"
echo >&2 "Example: T_github=ALTURL_%0%=https://github.com/vi/%0% envtemplater dive%github fdlinecombine%github -- submodule_update_alturl.sh --force"
exit 1
fi
while [ "$1" != '--' ]; do
if [[ $# == 0 ]]; then
echo >&2 "-- not found in command line"
exit 4;
fi
IFS="$ENVTEMPLATER_SEPARATOR"
Q=($1)
IFS='
'
#for i in ${Q[@]}; do
# echo "$i"
#done
TEMPLATE=T_${Q[${#Q[@]}-1]}
TEMPLATE_CONTENT=$(eval "echo \"\$$TEMPLATE\"")
if [ -z "$TEMPLATE_CONTENT" ]; then
echo >&2 "Template $TEMPLATE not found"
exit 2
fi
IFS="$ENVTEMPLATER_SEPARATOR"
TEMPLATE_ARRAY=($TEMPLATE_CONTENT)
IFS='
'
VALUE=""
MODE=val
for i in "${TEMPLATE_ARRAY[@]}"; do
if [[ $MODE == val ]]; then
VALUE="${VALUE}$i"
MODE=arg
else
if [[ $i -lt 0 || $i -gt ${#Q[@]}-1 ]] || ! [ $i -eq $i ]; then
echo >&2 "$i is out of bounds or not a number for $TEMPLATE_CONTENT in $1"
exit 3
fi
VALUE="${VALUE}${Q[$i]}"
MODE=val
fi
done
eval "export $VALUE"
shift
done
shift
exec "$@"
@kolomenkin
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment