16

I am trying to install and use nvm from the Jenkins execute shell script on Ubuntu server but I am getting this error:

16:00:21 /tmp/hudson5983664925305072739.sh: line 8: nvm: command not found

This is what I have tried those so far but no success:

#!/bin/bash

touch ~/.profile && source ~/.profile;
nvm current || echo "SSH NVM is being installed" &&  touch ~/.profile && curl -sL https://raw.githubusercontent.com/creationix/nvm/v0.31.0/install.sh -o install_nvm.sh && bash install_nvm.sh && source ~/.profile

echo "checking nvm"
bash ~/.nvm/nvm.sh;
nvm --version || exit 1;

Jenkins execute shell screenshot:

enter image description here

mirza
  • 5,685
  • 10
  • 43
  • 73

4 Answers4

22

Adding those solves the issue:

. ~/.nvm/nvm.sh
. ~/.profile
. ~/.bashrc
mirza
  • 5,685
  • 10
  • 43
  • 73
  • 5
    You should be able to use just `. ~/.nvm/nvm.sh` - the other two may configure a lot more than you need, or less (in some cases `~/.bashrc` will exit early if the current shell is non-interactive, i.e. running a shell script.) – RichVel May 23 '18 at 15:59
  • @RichVel is there a possibility to use this accross multiple `sh` invocations? – velop Mar 26 '21 at 13:49
  • 1
    Jenkins runs every `sh` command in a separate process, so you would have to find a way around this. If you are using Ubuntu you could look at using the `ENV` env var to point to a script that is run by the `dash` shell (default `/bin/sh`, see `man sh`) - but you would need to ensure that Jenkins runs `/bin/sh` as a login shell somehow. Perhaps the NodeJS plugin mentioned in another answer is a better route to explore. – RichVel Mar 27 '21 at 07:26
  • NOTE: When you use . ~/.bashrc in Consul Output you'll be see a lot of junk logs. To eliminate these lines you should use set +x before the . ~/.bashrc – Mohammad Ravanbakhsh Jun 11 '23 at 05:28
9

You need to remember that Jenkins is running commands in non-interactive shell so PATH is different from what a normal user has. One way to solve this problem is to invoke nvm with it absolute path.

Cosaquee
  • 724
  • 1
  • 6
  • 22
6

After struggling to get the suggestions above to work, I tried the NodeJS Jenkins plugin and it worked like a charm.

https://plugins.jenkins.io/nodejs/

Matthew S
  • 900
  • 3
  • 12
  • 26
4

Didn't quite get the answer I was looking for here but both led me to the obvious solution which is even in the README of nvm. The path isn't in the shell script of Jenkins so it can't find the executable.

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm

To figure out what your $HOME is you can run echo $HOME. For instance $HOME might look like this

export NVM_DIR="/var/lib/jenkins/.nvm"
Richard Herries
  • 280
  • 3
  • 4