Cannot run npm in a shell script

Jordane picture Jordane · Apr 13, 2017 · Viewed 15.2k times · Source

In a continuous deployment context I have a shell script executed to update and restart my app in the remote server

the script is:

ssh user@myserver <<'ENDSSH'
cd /opt/myapp
git pull
npm i
forever stop src
npm run staging
ENDSSH

the output is:

stdin: is not a tty
Already up-to-date.
-bash: line 3: npm: command not found
-bash: line 4: forever: command not found
-bash: line 5: npm: command not found

Note:

  • everything work if I ssh onto the remote server and enter those commands manually

  • node and npm are installed with nvm on the remote server which npm give /root/.nvm/versions/node/v6.10.0/bin/npm

Answer

rsp picture rsp · Apr 13, 2017

If your node and npm are installed in /root/.nvm/versions/node/v6.10.0/bin then adding this to your script should solve the problem:

PATH="/root/.nvm/versions/node/v6.10.0/bin:$PATH"

Alternatively you can try using absolute paths like:

/root/.nvm/versions/node/v6.10.0/bin/npm install

etc. but note that if you have your Node installed from the binary packages and not from sources then your shebang line in the npm binary will likely be #!/usr/bin/env node which will not work when the correct version of Node in the PATH - see this answer for more info:

When Node was installed from the sources then npm will have a correct shebang line with absolute path to the node binary and can be used wven when node is not in the PATH.