Skip to content

Instantly share code, notes, and snippets.

@trevmex
Last active December 20, 2015 19:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trevmex/6182086 to your computer and use it in GitHub Desktop.
Save trevmex/6182086 to your computer and use it in GitHub Desktop.
A shell script to read in the env.* variables from a .versions.conf file and replace them while in this directory only. Restores them on exit. This is meant to override `cd.` TODO: Make the cd command actually work...
#!/usr/bin/env bash
###
# cd override
#
# This replaces the builtin cd command
###
function init_local_env() {
SAVED_VAR=ENV$(echo $1 | sed -e s:/:_:g | tr "[:lower:]" "[:upper:]")_SAVED
NEW_VARS=$(cat .versions.conf | grep -e '^env\.' | sed -e 's/^env.//g' | tr '\n' ':' | sed -e 's/:$//g')
SAVED_IFS=$IFS
IFS=":"
for LINE in $NEW_VARS; do
ENV_VAR=$(echo $LINE | sed -e s:=.*$::g)
ENV_VAR_VAL=$(eval echo \$$ENV_VAR)
if [[ -z $(eval echo \$$SAVED_VAR) ]]; then
eval $SAVED_VAR="$ENV_VAR=$ENV_VAR_VAL"
else
eval $SAVED_VAR="$ENV_VAR=$ENV_VAR_VAL:\$$SAVED_VAR"
fi
eval $ENV_VAR=$ENV_VAR_VAL
done
IFS=$SAVED_IFS
SAVED_VAR=
SAVED_IFS=
NEW_VARS=
LINE=
ENV_VAR=
ENV_VAR_VAL=
}
function restore_local_env() {
SAVED_VAR=ENV$(echo $1 | sed -e s:/:_:g | tr "[:lower:]" "[:upper:]")_SAVED
SAVED_IFS=$IFS
IFS=":"
for LINE in $(eval echo \$$SAVED_VAR); do
ENV_VAR=$(echo $LINE | sed -e s:=.*$::g)
ENV_VAR_VAL=$(eval $LINE | sed -e s:^.*=::g)
eval $ENV_VAR=$ENV_VAR_VAL
done
IFS=$SAVED_IFS
eval $SAVED_VAR=
SAVED_VAR=
SAVED_IFS=
LINE=
}
if [[ -z $1 ]]; then
DIR=$HOME
else
DIR=$1
fi
if [[ -e $(pwd)/.versions.conf ]]; then
restore_local_env $(pwd)
fi
if [[ -e $DIR/.versions.conf ]]; then
init_local_env $DIR
fi
# This line obviously does not work, and should be replaces with cd override voodoo
cd $DIR
DIR=
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment