Last active
April 22, 2016 07:14
-
-
Save vi/6b73639a275f3b22261f to your computer and use it in GitHub Desktop.
Simplify setting multiple environment variables using templates
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
#!/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 "$@" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Please update your script from here:
https://gist.github.com/2bfb3ea296648f12049c1c8b3350baea.git