Skip to content

Instantly share code, notes, and snippets.

@msdigital
Created October 3, 2022 10:23
Show Gist options
  • Save msdigital/c19f5db17d420a29ddc77f340d753d97 to your computer and use it in GitHub Desktop.
Save msdigital/c19f5db17d420a29ddc77f340d753d97 to your computer and use it in GitHub Desktop.
bash automatic nvm node version switcher
##################################################
# Prerequisites
# This script only works with nvm
# Please install nvm first https://github.com/nvm-sh/nvm
#-------------------------------------------------
# Installation
# Copy this script into your home folder
# add "source ~/.autonvm" top the bottom of your .bashrc or .bash_profile
#-------------------------------------------------
# Usage
# 1. create a .node-version file in the project folder
# 2. add node version number into the .node-version file
# the File must only contain the node version number!!!
# 3. have fun coding :)
#
# or use this: echo "YOUR_NODE_VERSION">.node-version
##################################################
versionLookup(){
path=$(pwd)
while [[ "$path" != "" && ! -e "$path/$1" ]]; do
path=${path%/*}
done
echo "$path"
}
autonvm(){
cd "$@";
# Lookup version file .node-version
node_version_path=$(versionLookup .node-version | tr -d '[:space:]')
# .node-version File not found, try to use default node version
if [[ ! $node_version_path = *[^[:space:]]* ]]; then
declare node_default;
node_default=$(nvm version default);
# no default node version found
if [[ $node_default == "N/A" ]]; then
echo "No default version available. Check nvm ls or do nvm alias default xxxx";
fi
# .node-version File found
elif [[ -s $node_version_path/.node-version && -r $node_version_path/.node-version ]]; then
# get node version from .node-version file
declare nvm_version
nvm_version=$(echo $(<"$node_version_path"/.node-version) | tr -d '\r' | tr -d '\n')
# check if node version is available in nvm
declare nvm_check_version
nvm_check_version=$(nvm ls --no-colors "$nvm_version" | tail -1 | tr -d '\->*' | tr -d '[:space]')
# node version not available in nvm
if [[ $nvm_check_version == "N/A" ]]; then
echo "Node version not installed."
# node version available, switch node version
elif [[ $(nvm current) != "$nvm_check_version" ]]; then
nvm use $nvm_version
fi
fi
}
alias cd='autonvm'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment