Skip to content

Instantly share code, notes, and snippets.

@MatthewZaso
Last active April 14, 2023 22:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MatthewZaso/7d16fa5a4e7feb3c6e2661c9a5b7a097 to your computer and use it in GitHub Desktop.
Save MatthewZaso/7d16fa5a4e7feb3c6e2661c9a5b7a097 to your computer and use it in GitHub Desktop.
Automate the installation of both NVM and the currently defined .nvmrc node version
#!/bin/bash
export NVM_DIR=$HOME/.nvm;
source $NVM_DIR/nvm.sh;
# Check if xcode command line tools are installed (required)
if xcode-select -p &> /dev/null && xcrun --version &> /dev/null; then
echo "XCode command line tools are installed ✅"
else
echo "XCode command line tools need to first be installed. Please install them at the next prompt and then run this script again."
xcode-select --install
exit 1
fi
# Check if nvm is installed
if command -v nvm &> /dev/null
then
echo "nvm is installed ✅"
else
echo "nvm is not installed. Installing now"
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.3/install.sh | bash
if [[ -d "${NVM_DIR}" ]]; then
NVM_EXPORT='
export NVM_DIR="$([ -z "${XDG_CONFIG_HOME-}" ] && printf %s "${HOME}/.nvm" || printf %s "${XDG_CONFIG_HOME}/nvm")"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm
'
SHELL_TYPE=$(echo $SHELL)
if [[ $SHELL_TYPE == *"zsh"* ]]; then
echo "Updating zshrc file..."
echo $NVM_EXPORT >> ~/.zshrc
source ~/.bash_profile
elif [[ $SHELL_TYPE == *"bash"* ]]; then
echo "Updating bash_profile..."
echo $NVM_EXPORT >> ~/.bash_profile
source ~/.bash_profile
else
echo "Unsupported shell: $SHELL_TYPE"
exit 1
fi
else
echo "The NVM directory already exists. Skipping profile updates..."
fi
fi
# Check if the node version from package.json is installed
NODE_VERSION=$(cat .nvmrc)
if ! nvm ls | grep -q $NODE_VERSION; then
echo "$NODE_VERSION is not installed. Installing..."
nvm install $NODE_VERSION
fi
# Use the specified node version
echo "Switching node version to version: $NODE_VERSION..."
nvm use $NODE_VERSION
# Set current node version to default
echo "Setting default node version to: $NODE_VERSION..."
nvm alias default $NODE_VERSION
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment