Skip to content

Instantly share code, notes, and snippets.

@vielhuber
Last active February 19, 2026 16:17
Show Gist options
  • Select an option

  • Save vielhuber/021453a7e908f9487917835107ad6ce7 to your computer and use it in GitHub Desktop.

Select an option

Save vielhuber/021453a7e908f9487917835107ad6ce7 to your computer and use it in GitHub Desktop.
Auto switch version on command line based on env files #php #js #python
# auto switch
find_up() {
local file="$1"
local dir="$PWD"
while [[ "$dir" != "/" ]]; do
if [[ -f "$dir/$file" ]]; then
echo "$dir/$file"
return 0
fi
dir="$(dirname "$dir")"
done
[[ -f "/$file" ]] && echo "/$file" && return 0
return 1
}
file_sig() {
local f="$1"
[[ -f "$f" ]] || return 1
stat -c '%Y:%s' "$f" 2>/dev/null
}
auto_switch() {
if [[ $PWD == $PREV_PWD ]]; then
return
fi
PREV_PWD=$PWD
local nvmrc phprc envrc
nvmrc=$(find_up ".nvmrc")
phprc=$(find_up ".phprc")
envrc=$(find_up ".envrc")
if [[ -n "$nvmrc" ]]; then
if [[ "$nvmrc" != "$PREV_NVMRC" ]]; then
PREV_NVMRC="$nvmrc"
PREV_NVMRC_SIG=$(file_sig "$nvmrc")
nvm use --silent && echo "switch to node $(cat "$nvmrc") (from $nvmrc)"
fi
else
PREV_NVMRC=""
PREV_NVMRC_SIG=""
fi
if [[ -n "$phprc" ]]; then
if [[ "$phprc" != "$PREV_PHPRC" ]]; then
PREV_PHPRC="$phprc"
PREV_PHPRC_SIG=$(file_sig "$phprc")
sudo update-alternatives --set php /usr/bin/php$(cat "$phprc") \
&& echo "switch to php $(cat "$phprc") (from $phprc)"
fi
else
PREV_PHPRC=""
PREV_PHPRC_SIG=""
fi
if [[ -n "$envrc" ]]; then
if [[ "$envrc" != "$PREV_ENVRC" ]]; then
PREV_ENVRC="$envrc"
PREV_ENVRC_SIG=$(file_sig "$envrc")
source "$(cat "$envrc")/bin/activate" \
&& echo "switch to python $(cat "$envrc") (from $envrc)"
fi
else
PREV_ENVRC=""
PREV_ENVRC_SIG=""
fi
}
export PROMPT_COMMAND=auto_switch
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment