How to run NVM command from bash script

不想你离开。 提交于 2019-12-01 06:13:16

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