Skip to content

Instantly share code, notes, and snippets.

Created January 15, 2018 20:52
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
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")"
# Source virtual environment if it exists.
if [[ -f "$base_dir/$venv_dir/bin/activate" ]]; then
source "$base_dir/$venv_dir/bin/activate"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment