How can I call "nvm use" in a bash script, and have the selected node version retained after the script executes?

Viewed 2084

For a build process that requires updating from Node.js 12 to 14, I'd like a bash script to detect whether nvm is installed, and, if so, do nvm use v14 (or nvm install v14 if necessary), and then I want the nvm-selected node version to stick at 14 after the bash script terminates, not just for the duration of the script.

I can switch to v14 with this script, but after the script has terminated, the shell environment remains at v12:

#!/bin/bash

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"
source ~/.bashrc

nvm --version
echo $NVM_BIN
node --version
nvm use v14
echo $NVM_BIN
node --version

Just executing the nvm command in a bash script is a pain because nvm isn't a true command, but a shell function, and the script has to use the first three lines to set up nvm for the script.

The output is:

0.33.11
/home/pi/.nvm/versions/node/v12.21.0/bin
v12.21.0
Now using node v14.16.0 (npm v6.14.11)
/home/pi/.nvm/versions/node/v14.16.0/bin
v14.16.0

When the script is finished, however:

enter image description here

I think the trick might be making sure the environment variable NVM_BIN persists at the v14 path when the script exits, but I don't know how to do that. In fact, I think it's generally not allowed for the shell in which a script executes to change environment variables in the parent shell.

The nvm commmand, however, is itself a shell script, and whatever it does is persistent after it's done executing. There should be some way for me to make this happen too.

2 Answers

I think if you set an alias with nvm for default,

nvm alias default 14.0.0

the node version will persist across any new terminal instances.

To have the selected node version after the script executes you can run it like this:

. change-node-version.sh

script

node --version
nvm use 14.18.0
node --version

output

then:

node --version
āžœ  v14.18.0
Related