Last active
September 4, 2024 20:36
-
-
Save mbrammer/baa82c9ac02dcc31664a9590aed967b1 to your computer and use it in GitHub Desktop.
Auto-switch NVM Node version when switching into directory with .nvmrc file
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
# | |
# Run 'nvm use' automatically every time there's | |
# a .nvmrc file in the directory. Also, revert to default | |
# version when entering a directory without .nvmrc | |
# | |
enter_directory() { | |
if [[ $PWD == $PREV_PWD ]]; then | |
return | |
fi | |
PREV_PWD=$PWD | |
if [[ -f ".nvmrc" ]]; then | |
# Read the Node.js version from .nvmrc | |
NODE_VERSION=$(cat .nvmrc | tr -d '[:space:]') | |
# Check if the Node.js version is already installed | |
if ! nvm ls "$NODE_VERSION" >/dev/null 2>&1; then | |
# If not installed, install it | |
nvm install "$NODE_VERSION" | |
fi | |
# Use the specified version | |
nvm use "$NODE_VERSION" | |
NVM_DIRTY=true | |
elif [[ $NVM_DIRTY = true ]]; then | |
nvm use default | |
NVM_DIRTY=false | |
fi | |
} | |
export PROMPT_COMMAND="$PROMPT_COMMAND; enter_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
# | |
# Run 'nvm use' automatically every time there's | |
# a .nvmrc file in the directory. Also, revert to default | |
# version when entering a directory without .nvmrc | |
# | |
enter_directory() { | |
if [[ $PWD == $PREV_PWD ]]; then | |
return | |
fi | |
PREV_PWD=$PWD | |
if [[ -f ".nvmrc" ]]; then | |
# Read the Node.js version from .nvmrc | |
NODE_VERSION=$(cat .nvmrc | tr -d '[:space:]') | |
# Check if the Node.js version is already installed | |
if ! nvm ls "$NODE_VERSION" >/dev/null 2>&1; then | |
# If not installed, install it | |
nvm install "$NODE_VERSION" | |
fi | |
# Use the specified version | |
nvm use "$NODE_VERSION" | |
NVM_DIRTY=true | |
elif [[ $NVM_DIRTY = true ]]; then | |
nvm use default | |
NVM_DIRTY=false | |
fi | |
} | |
export PROMPT_COMMAND="$PROMPT_COMMAND; enter_directory" | |
prmptcmd() { eval "$PROMPT_COMMAND" } | |
precmd_functions=(prmptcmd) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment