Set node version with NVM or install if not available.

Solution 1:

Have you tried grepping nvm ls?

. /usr/local/opt/nvm/nvm.sh
if [[ $(nvm ls | grep v6.9.1) == "" ]]; then
  nvm install v6.9.1
else
  nvm use v6.9.1
fi

Is it any faster than using nvm install v6.9.1 for you?

EDIT: You can also set a default version that will always be loaded by default. You can do it by running nvm alias default 6.9.1.

You can try changing your script to this:

if [[ $(node -v) != "v6.9.5" ]]; then
  nvm install v6.9.5
  nvm alias default v6.9.5
fi

It will take a little long, but just for the first time

Solution 2:

In the current version of nvm, nvm install does not reinstall node if it's already installed.

Examples:

$ nvm install v16.14.2
v16.14.2 is already installed.

# Or using .nvmrc
$ nvm install
v16.14.2 is already installed.

Note however, if you specify an ambiguous version such as v16 and a newer version of v16 is available, then nvm will download and install the newer version, ignoring your older version of v16.

$ node --version
v16.0.4
$ nvm install v16
Downloading and installing node v16.14.2...