I want to run an NVM
command from bash script i.e. nvm use 0.12.7
. So, I have written in bash file:
#!/bin/bash
. ~/.nvm/nvm.sh
nvm use 0.12.7
And then run the command in the terminal as sudo ./script.sh
(script.sh is my bash file where above code is written). It gives me the result Now using node v0.12.7
. But when I check was the version activated or not, I found no affect. i.e. I ran command nvm ls
and found the result as:
v0.12.0
v0.12.7
That's mean version 0.12.7
was not being activated. So, which things should I write in bash script as I can active node version from bash file.
One of the advantages of nvm
is that you don't need to use sudo
to install versions or to switch to another version. I'm not sure why you are using sudo
in your nvm
command.
The problem, as others have also said, is that the version is changed in a sub-shell. So the version in your "real" shell is not changed.
You can accomplish this by running your script with .
(dot space) in front of it. That will make the script to be able to change stuff in your current shell.
This is my ~/bin/nvm-use-4
script:
. /usr/local/opt/nvm/nvm.sh
nvm use 4
And using it:
prawie:~$ nvm current
v0.10.29
prawie:~$ . nvm-use-4
Now using node v4.2.1
prawie:~$ nvm current
v4.2.1
If you are forced to use sudo
here, I don't think it's possible to accomplish what you want, because the sudo'ed command is run in a sub-shell.
Unfortunately, you have not told use why you want to do this or what you want to accomplish. There could be better solutions to solve your problem. For example, if you want to always use a specific version of node.js
when you open a new shell, you could add the following line to .profile
, .bashrc
or equivalent file:
nvm use 0.12.7
来源:https://stackoverflow.com/questions/34408298/how-to-run-nvm-command-from-bash-script