How to run NVM command from bash script

谁说我不能喝 提交于 2019-11-30 17:11:24

问题


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.


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!