Bash script to install nodejs automatically on Linux

Nodejs has multiple versions that different software developed with nodejs may require a specific version. The following is a bash script to make it easy to insall the version of your choice:

#!/bin/bash

# Script to install Node.js using NVM on Ubuntu without sudo

# Function to install NVM
install_nvm() {
    echo "Installing NVM..."
    curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
    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
}

# Check if NVM is installed
if ! command -v nvm &> /dev/null
then
    install_nvm
else
    echo "NVM is already installed."
fi

# Ask user for the Node.js version to install
read -p "Enter the Node.js version you want to install (e.g., 14.17.0): " node_version

# Install Node.js using NVM
nvm install $node_version
nvm use $node_version

echo "Node.js version $node_version has been installed."

Instructions:

1.  Copy this script into a file, for example install_node.sh.
2.  Give the script execute permission: chmod +x install_node.sh.
3.  Run the script: ./install_node.sh.
4.  Follow the prompts to install the desired version of Node.js.

This script first checks if NVM is installed, installs it if not, and then proceeds to install the specified version of Node.js. Remember to run this script as a regular user, not as root, since it’s designed to work without sudo.

Leave a Reply

Your email address will not be published.