Skip to content

Instantly share code, notes, and snippets.

@fmeynadier
Created November 24, 2021 16:48
A fast way to determine pyenv version
#!/bin/bash
# Inspired by https://gitlab.com/bersace/powerline.bash
__retval=""
__find_parent() {
local cwd="$1"
local name="$2"
__retval=()
while [ "$cwd" ] ; do
if [ -e "$cwd/$name" ] ; then
__retval=("$cwd/$name")
return
fi
cwd="${cwd%/*}"
done
}
__pyenv_version_name() {
local dir="$PWD"
# Case 1: env variable PYENV_VERSION is set
__retval=("${PYENV_VERSION-}")
if [ -n "${_retval[*]}" ] ; then
return
fi
# Case 2: a .python_version file is found here or case 3: in a parent dir
__find_parent "${dir}" .python-version
if [ -n "${__retval[*]}" ] && readarray __retval < "${__retval[*]}" 2>/dev/null ; then
# read found something and recorded it, we're OK
return
fi
# Case 4: a ${PYENV_ROOT}/version file exists
if [ -v PYENV_ROOT ] ; then
if [ -f "${PYENV_ROOT}/version" ] ; then
readarray -n 1 -t __retval < "${PYENV_ROOT}"/version 2>/dev/null
fi
fi
return
}
__pyenv_version_name
echo $__retval
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment