0

I have a cronjob very simple:

#! /bin/bash -l

ps cax | grep PM2
if [ $? -eq 0 ]; then
  echo $(date -u) - "PM2 is running."
else
  echo $(date -u) - "Restarting PM2."
  cd ~/public_html/
  /home/test/.nvm/versions/node/v10.21.0/bin/pm2 start index.js
fi

The problem appears when my hosting updates the node, and path has change in:

/home/test/.nvm/versions/node/v10.22.0/bin/pm2

and of course the cron fails to run the command. It's there a way to dynamically get that new version folder name?

tripleee
  • 175,061
  • 34
  • 275
  • 318
AlexM
  • 1
  • Tangentially, [Why is testing ”$?” to see if a command succeeded or not, an anti-pattern?](https://stackoverflow.com/questions/36313216/why-is-testing-to-see-if-a-command-succeeded-or-not-an-anti-pattern) – tripleee Oct 17 '20 at 08:58

1 Answers1

0

If you always have only one changing version, you could use find:

pm2=$(find /home/test/.nvm/versions/node -name pm2)
$pm2 start index.js

If node might contain other files named pm2, you could make sure it's in a bin directory:

pm2=$(find /home/test/.nvm/versions/node/*/bin -name pm2)
#or
pm2=$(find /home/test/.nvm/versions/node/ -name pm2 -wholename '*/bin/*')

And you could also execute it directly:

find /home/test/.nvm/versions/node/*/bin -name pm2 -exec "{}" start index.js \;

Look at man find for it's many options.

But you could also simply call it like

/home/test/.nvm/versions/node/*/bin/pm2 start index.js
mivk
  • 13,452
  • 5
  • 76
  • 69