简体   繁体   English

如何从bash脚本运行NVM命令

[英]How to run NVM command from bash script

I want to run an NVM command from bash script ie nvm use 0.12.7 . 我想从bash脚本运行NVM命令,即nvm use 0.12.7 So, I have written in bash file: 所以,我写了bash文件:

#!/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). 然后在终端中以sudo ./script.sh是我的bash文件,上面的代码被写入)中运行命令。 It gives me the result Now using node v0.12.7 . Now using node v0.12.7给我结果。 But when I check was the version activated or not, I found no affect. 但是当我检查版本是否激活时,我发现没有影响。 ie I ran command nvm ls and found the result as: 即我运行命令nvm ls ,发现结果为:

v0.12.0
v0.12.7

That's mean version 0.12.7 was not being activated. 这意味着未激活0.12.7版本。 So, which things should I write in bash script as I can active node version from bash file. 因此,我应该在bash脚本中编写哪些内容,因为我可以从bash文件激活节点版本。

One of the advantages of nvm is that you don't need to use sudo to install versions or to switch to another version. 其中一个优点nvm是,你不需要使用sudo安装版本或切换到另一个版本。 I'm not sure why you are using sudo in your nvm command. 我不确定为什么在nvm命令中使用sudo

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. 这将使脚本能够更改当前shell中的内容。

This is my ~/bin/nvm-use-4 script: 这是我的~/bin/nvm-use-4脚本:

. /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. 如果您被迫在此处使用sudo ,我认为不可能完成您想要的事情,因为sudo'ed命令在子外壳中运行。

Unfortunately, you have not told use why you want to do this or what you want to accomplish. 不幸的是,您没有告诉use为什么要这样做或想要完成什么。 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: 例如,如果要在打开新的外壳程序时始终使用特定版本的node.js ,则可以node.js下行添加到.profile.bashrc或等效文件中:

nvm use 0.12.7

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM