2

my shell script

#!/bin/bash    
pm2 start server.js 

my crontab task

* * * * * /home/ec2-user/abcd/test.sh > /home/ec2-user/cron.log 2>&1

What I got from the log:

home/ec2-user/abcd/test.sh: line 2: pm2: command not found

how to fix it?

Remark:

1.When I execute ./test.sh, it runs normally

2.which pm2 - shows

~/.nvm/versions/node/v14.16.1/bin/pm2
JustFun2020
  • 121
  • 2
  • 7

2 Answers2

2

The problem may be because of that PATH environment variable hasn't been set when the cron job is being executed and this is why your shell script can't find pm2. You have to enter the complete address of pm2.

Example if pm2 is in /usr/bin/:

#!/bin/bash
/usr/bin/pm2 start server.js

Or you may want to just set PATH env before the command you want to execute in you shell script.

In normal, when you execute the program in you terminal, the environment variables are set properly. This is why you can run your shell script in your terminal without any problem.

zbx0310
  • 64
  • 8
  • after executing the above code - /usr/bin/pm2: No such file or directory – JustFun2020 Jun 23 '21 at 02:59
  • Enter ```whereis pm2```. And see where it is located. Then replace it with the address I used in the code. – zbx0310 Jun 23 '21 at 03:00
  • /home/ec2-user/.nvm/versions/node/v14.16.1/bin/pm2 - but I got - /usr/bin/env: node: No such file or directory – JustFun2020 Jun 23 '21 at 03:04
  • ```/home/ec2-user/.nvm/versions/node/v14.16.1/bin/pm2 start server.js``` So it doesn't work ? – zbx0310 Jun 23 '21 at 03:14
  • shows /usr/bin/env: node: No such file or directory – JustFun2020 Jun 23 '21 at 03:16
  • @JustFun2020 check it reference this "https://stackoverflow.com/questions/26320901/cannot-install-nodejs-usr-bin-env-node-no-such-file-or-directory" – Victor Lee Jun 23 '21 at 03:31
  • 1
    Thanks @VictorLee. Your referenced link has a relevant discussion to solve a similar issue for me. To solve the below error which @JustFun2020 is getting `/usr/bin/env: node: No such file or directory ` We need to make a symlink which can be done with the below command `sudo ln -s "$(which node)" /usr/bin/node` Here `"$(which node)"` will fetch the Node version for you. – Shadab Jan 31 '23 at 11:50
0

Set the path command like mentioned in the other answer.

PATH="/usr/bin:/bin:/home/ec2-user/.nvm/versions/node/v14.16.1/bin"

Next, locate the path to your server.js file and add the pm2 start command with the path.

pm2 start /home/ec2-user/ .....your path to the file..... /server.js

Complete code:

#!/bin/bash
PATH="/usr/bin:/bin:/home/ec2-user/.nvm/versions/node/v14.16.1/bin"
pm2 start /home/ec2-user/ .....your path to the file..... /server.js
stromyc
  • 488
  • 6
  • 13