Skip to content

Instantly share code, notes, and snippets.

@chriswburke
Forked from tribou/nvm_auto_switching.sh
Created January 9, 2020 02:40
Show Gist options
  • Save chriswburke/1dd7a597525a5bfcbaab75c6be6003c7 to your computer and use it in GitHub Desktop.
Save chriswburke/1dd7a597525a5bfcbaab75c6be6003c7 to your computer and use it in GitHub Desktop.
Use PROMPT_COMMAND and nvm to auto-switch versions of node
#!/bin/bash
# Activate a version of Node that is read from a text file via NVM
function use_node_version()
{
local TEXT_FILE_NAME="$1"
local CURRENT_VERSION=$([ -n "$HAS_NVM" ] && nvm current)
local PROJECT_VERSION=$([ -n "$HAS_NVM" ] && nvm version $(cat "$TEXT_FILE_NAME"))
# If the project file version is different than the current version
if [ "$CURRENT_VERSION" != "$PROJECT_VERSION" ]
then
[ -n "$HAS_NVM" ] && nvm use "$PROJECT_VERSION"
fi
}
# Read the .nvmrc and switch nvm versions if exists upon dir changes
function read_node_version()
{
# Only run if we actually changed directories
if [ "$PWD" != "$READ_NODE_VERSION_PREV_PWD" ]
then
export READ_NODE_VERSION_PREV_PWD="$PWD";
# If there's an .nvmrc here
if [ -e ".nvmrc" ]
then
use_node_version ".nvmrc"
return
fi
# If there's a .node-version here
if [ -e ".node-version" ]
then
use_node_version ".node-version"
return
fi
fi
}
[[ $PROMPT_COMMAND != *"read_node_version"* ]] && export PROMPT_COMMAND="$PROMPT_COMMAND read_node_version ;"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment