Skip to content

Instantly share code, notes, and snippets.

@defrank
Created January 15, 2018 20:52
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 defrank/9c513056f7246d70758cb8ae1c90e823 to your computer and use it in GitHub Desktop.
Save defrank/9c513056f7246d70758cb8ae1c90e823 to your computer and use it in GitHub Desktop.
Override builtin cd to source closest virtual environment
# Source closest virtual environment, ``venv``, if exists in any parent
# directory.
cd () {
local venv_dir="venv" prevpwd="$PWD"
builtin cd "$@"
if [ "$prevpwd" != "$PWD" ]; then
local base_dir="$PWD"
# Always try to deactivate for nested virtual environments.
deactivate &>/dev/null
# Find the closest parent directory with ``venv``.
while [[ ! -d "$base_dir/$venv_dir" ]] && [[ "$base_dir" != '/' ]]; do
base_dir="$(dirname "$base_dir")"
done
# Source virtual environment if it exists.
if [[ -f "$base_dir/$venv_dir/bin/activate" ]]; then
source "$base_dir/$venv_dir/bin/activate"
fi
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment