无法使用bash脚本中的nvm

use*_*717 6 shell node.js npm nvm

我正在尝试编写一个shell脚本来自动化我的开发环境设置(安装python,nvm,node,mongo等...).我正在使用nvm来安装Node.它会告诉您关闭并重新打开终端以开始使用nmv命令.我尝试使用.bashrc和.profile来使命令立即可用,因此我可以继续使用nvm install运行脚本,但它不起作用.

以下是与安装NVM/Node相关的脚本部分:

#install nvm and latest node version
# sourcing profile and bashrc is not working here. nvm does not execute the next two lines to install node.

wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.30.2/install.sh | bash
source ~/.profile
source ~/.bashrc
nvm install 5.0
nvm alias default node
Run Code Online (Sandbox Code Playgroud)

我收到这些消息,但请注意我已经运行了脚本并且NVM/Node已经安装并正常工作.我也可以在同一个终端中使用nvm和node,在完成后运行脚本.它只是在脚本中不起作用.

=> Downloading nvm from git to '/home/myDir/.nvm'
=> fatal: destination path '/home/myDir/.nvm' already exists and is not an empty directory.
fatal: Not a git repository (or any of the parent directories): .git
fatal: Not a git repository (or any of the parent directories): .git

=> Source string already in /home/myDir/.bashrc
=> Close and reopen your terminal to start using nvm
./install-programs.sh: line 27: nvm: command not found
./install-programs.sh: line 28: nvm: command not found
Run Code Online (Sandbox Code Playgroud)

MrE*_*MrE 25

如果您在主 shell 上运行 nvm,您只需要添加:

export NVM_DIR=$HOME/.nvm;
source $NVM_DIR/nvm.sh;
Run Code Online (Sandbox Code Playgroud)

在你的脚本中

  • 源代码在 POSIX 中不可用...如果您关心 docker alpine 或 Android termux 等精简 Linux 映像的可移植性,请使用“.”。这与 `if [ -f "$NVM_DIR/nvm.sh" ]; 配对 then` 帮助我使用可用的 `.nvmrc`。这是要点https://gist.github.com/simov/cdbebe2d65644279db1323042fcf7624 (2认同)

小智 10

只需将其放在脚本之上即可:

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This loads nvm bash_completion
Run Code Online (Sandbox Code Playgroud)

在这里工作就像一个魅力。


Ste*_*las 7

这对我有用.

首先使用SSH或控制台安装nvm(一次和单独):

$ wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.30.2/install.sh | bash
Run Code Online (Sandbox Code Playgroud)

然后在您的脚本中加载您的配置文件,如下所示:

. ~/.nvm/nvm.sh
. ~/.profile
. ~/.bashrc
Run Code Online (Sandbox Code Playgroud)

并且有一些运气nvm应该在脚本中可用.

nvm install 4.4.2
Run Code Online (Sandbox Code Playgroud)

田田!

  • 添加 . ~/.nvm/nvm.sh 在使用它之前对我有用,谢谢! (2认同)