Search code examples
shellcronpm2cron-task

(shell script file) pm2: command not found in crontab task


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

Solution

  • 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.