Skip to content

Instantly share code, notes, and snippets.

@martin-martin
Created November 17, 2022 13:50
Show Gist options
  • Save martin-martin/5de751350f682fcc50e0750977b3fce2 to your computer and use it in GitHub Desktop.
Save martin-martin/5de751350f682fcc50e0750977b3fce2 to your computer and use it in GitHub Desktop.
# Auto-activate virtual environments on cd when it's called `venv/`
# auto activate virtualenv
# Modified solution based on https://stackoverflow.com/questions/45216663/how-to-automatically-activate-virtualenvs-when-cding-into-a-directory/56309561#56309561
function cd() {
builtin cd "$@"
## Default path to virtualenv in your projects
DEFAULT_ENV_PATH="./venv"
## If env folder is found then activate the vitualenv
function activate_venv() {
if [[ -f "${DEFAULT_ENV_PATH}/bin/activate" ]] ; then
source "${DEFAULT_ENV_PATH}/bin/activate"
echo "Activating ${VIRTUAL_ENV}"
fi
}
if [[ -z "$VIRTUAL_ENV" ]] ; then
activate_venv
else
## check the current folder belong to earlier VIRTUAL_ENV folder
# if yes then do nothing
# else deactivate then run a new env folder check
parentdir="$(dirname ${VIRTUAL_ENV})"
if [[ "$PWD"/ != "$parentdir"/* ]] ; then
echo "Deactivating ${VIRTUAL_ENV}"
deactivate
activate_venv
fi
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment