无法从 bash 脚本使用 nvm

问题描述 投票:0回答:7

我正在尝试编写一个 shell 脚本来自动设置我的开发环境(安装 python、nvm、node、mongo 等...)。我正在使用 nvm 来安装 Node.js。它告诉您关闭并重新打开终端以开始使用 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

我收到这些消息,但请注意,我已经运行了脚本,并且 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
node.js shell npm nvm
7个回答
80
投票

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

export NVM_DIR=$HOME/.nvm;
source $NVM_DIR/nvm.sh;

在你的脚本中


31
投票

这对我有用。

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

$ wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.30.2/install.sh | bash

然后在您的脚本中,按如下方式加载您的个人资料:

. ~/.nvm/nvm.sh
. ~/.profile
. ~/.bashrc

如果运气好的话,

nvm
应该可以在脚本中使用。

nvm install 4.4.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

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


4
投票

现在,您可以简单地执行以下操作:

env NODE_VERSION=<dd> /home/<user>/.nvm/nvm-exec npm run front

简单地采购 nvm.sh 对我来说不起作用(从 systemd .service 文件),路径不包括

~/.nvm...

信用到期的信用:https://gist.github.com/joepie91/73ce30dd258296bd24af23e9c5f761aa#gistcomment-2215867


2
投票

这个脚本对我来说效果很好:

#!/usr/bin/env bash

if [ ! -d ~/.nvm ]; then

  curl https://raw.githubusercontent.com/creationix/nvm/v0.11.1/install.sh | bash
  source ~/.nvm/nvm.sh
  source ~/.profile
  source ~/.bashrc
  nvm install 5.0
  npm install
  npm run front
fi

0
投票

确保服务器/您的机器中安装了 NVM 按以下格式修改您的 shell 脚本,我们使用的 shell 脚本在客户端和服务器中使用两个不同的节点版本。请检查这是否适合您?

echo "Removing build files..";
rm -rf server/public/build
echo "Generating New Build....";
source $NVM_DIR/nvm.sh;
cd client
nvm use 14.16.1;
echo "Building Application";
npm install --legacy-peer-deps;
npm run build
echo "Building App Ends";
cd ..
nvm use 16.13.0;
npm install --legacy-peer-deps

0
投票

我发现此链接很有帮助:NVM。我们需要找到我们正在使用哪个 shell。

下面的脚本对我有用。


echo "starting redis required for backend";
pm2 start "redis-server" --name redis_c

# source ~/.bashrc
. ~/.profile

cd project_dir;
echo "inside project_dir";

nvm use;
git pull origin main;


.... more scripts.
© www.soinside.com 2019 - 2024. All rights reserved.