Skip to content

Instantly share code, notes, and snippets.

@hed0rah
Created March 6, 2026 05:06
Show Gist options
  • Select an option

  • Save hed0rah/0b81e556edea9a99631c7c3979e77c69 to your computer and use it in GitHub Desktop.

Select an option

Save hed0rah/0b81e556edea9a99631c7c3979e77c69 to your computer and use it in GitHub Desktop.
venv-activate.sh
#!/usr/bin/env bash
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
echo "ERROR: Script must be sourced" >&2
exit 1
fi
declare -a venvs=()
while IFS= read -r -d '' dir; do
venvs+=("${dir#./}")
done < <(find . -maxdepth 1 -type d ! -name '.' -exec test -f {}/pyvenv.cfg \; -print0 2>/dev/null)
for name in venv .venv env .env virtualenv venv-* .venv-*; do
if [[ -d "$name" && -f "$name/bin/activate" ]] && ! printf '%s\n' "${venvs[@]}" | grep -qxF "$name"; then
venvs+=("$name")
fi
done
mapfile -t venvs < <(printf '%s\n' "${venvs[@]}" | sort -u)
if [[ ${#venvs[@]} -eq 0 ]]; then
echo "No venv found" >&2
return 1
fi
if [[ ${#venvs[@]} -eq 1 ]]; then
selected="${venvs[0]}"
else
for i in "${!venvs[@]}"; do
printf "%d) %s\n" "$((i+1))" "${venvs[i]}"
done
read -rp "Select number: " num
selected="${venvs[num-1]}"
fi
echo "Selected: $selected"
echo "Activating: $PWD/$selected/bin/activate"
if source "$PWD/$selected/bin/activate"; then
echo "Python: $(python --version 2>&1)"
echo "VIRTUAL_ENV: ${VIRTUAL_ENV}"
else
echo "Activation failed" >&2
return 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment