Created
June 27, 2025 11:34
-
-
Save rogerthomas84/0438bafa4ed8e50647dfa09452510253 to your computer and use it in GitHub Desktop.
Automatically source venv with bash
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
function activate_venv_if_exists() { | |
local current_dir="$PWD" | |
local found_venv="" | |
# Loop upwards through the directory hierarchy | |
while [[ "$current_dir" != "/" && "$current_dir" != "" ]]; do | |
if [[ -d "$current_dir/venv" ]]; then | |
found_venv="$current_dir/venv" | |
break | |
fi | |
current_dir=$(dirname "$current_dir") | |
done | |
if [[ -n "$found_venv" ]]; then | |
# Check if a virtual environment is already active | |
# This prevents reactivating the same venv or activating a child venv if parent is active | |
if [[ -z "$VIRTUAL_ENV" || "$VIRTUAL_ENV" != "$found_venv" ]]; then | |
# Deactivate any currently active virtual environment if it's different | |
if [[ -n "$VIRTUAL_ENV" ]]; then | |
deactivate 2>/dev/null | |
fi | |
source "$found_venv/bin/activate" | |
echo "Activated: $(basename "$found_venv")" # Optional: provides feedback | |
fi | |
else | |
# If no venv is found and one is currently active, deactivate it | |
if [[ -n "$VIRTUAL_ENV" ]]; then | |
deactivate 2>/dev/null | |
echo "Deactivated Python venv" # Optional: provides feedback | |
fi | |
fi | |
} | |
PROMPT_COMMAND="activate_venv_if_exists; $PROMPT_COMMAND" | |
activate_venv_if_exists |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment