Skip to content

Instantly share code, notes, and snippets.

@euphoris
Forked from dahlia/cd_hook.sh
Created August 20, 2012 16:20
Show Gist options
  • Save euphoris/3405460 to your computer and use it in GitHub Desktop.
Save euphoris/3405460 to your computer and use it in GitHub Desktop.
[virtualenvwrapper] automatic workon hook on cd
export PROJECTS_HOME="$HOME/Projects"
function has_virtualenv__() {
if [[ ${PWD##$PROJECTS_HOME} != $PWD ]]; then
IFS="/" read -ra ADDR <<< "${PWD##$PROJECTS_HOME}"
venvname=${ADDR[1]}
cur_env=${VIRTUAL_ENV##$WORKON_HOME}
if [[ $venvname != "" ]] && [[ -d "$WORKON_HOME/$venvname" ]]; then
if [[ ${cur_env:1} != $venvname ]]; then
workon "$venvname"
fi
else
if [[ $VIRTUAL_ENV != "" ]]; then
deactivate
fi
fi
else
if [[ $VIRTUAL_ENV != "" ]]; then
deactivate
fi
fi
}
function venv_cd() {
builtin cd "$@" && has_virtualenv__
}
alias cd=venv_cd
@juanpabloaj
Copy link

@pquentin
Copy link

@juanpabloaj that only allows you to cd on workon, but not to workon on cd.

@euphoris with ZSH, you can define a chpwd function that will be called on each working directory change. Also note that read -a is a GNU extension which does not work out of the box on OS X and BSD. I used echo "${PWD##$PROJECTS_HOME}" | cut -d'/' -f2) instead.

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