Last active
December 2, 2025 15:08
-
-
Save tartley/953bea073c2e8f830ad3eba078b6e238 to your computer and use it in GitHub Desktop.
Automatically activate/deactivate virtualenvs in `.venv` when we `cd` into their parent directory
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # auto activate virtualenvs ------------------ | |
| # I suspect this could be rewritten to just use VIRTUAL_ENV directly, | |
| # without needing the $parentdir variable at all. | |
| function cd() { | |
| builtin cd "$@" | |
| # If we move out of a previous parentdir, deactivate the previous venv | |
| if [[ -n "$parentdir" && "$PWD"/ != "$parentdir"/* ]]; then | |
| deactivate | |
| unset parentdir | |
| fi | |
| # If there is a virtualenv, activate it | |
| if [[ -d ".venv" && -f ".venv/bin/activate" ]]; then | |
| source ".venv/bin/activate" | |
| parentdir="$(dirname $VIRTUAL_ENV)" | |
| fi | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment