Thursday, June 16, 2016

SetUp a cron to restart node project if it's not running

Check if node project is running using swagger and start if not running.

#!/bin/bash

###edit the following
service=swagger
email=email@yourdomain.com.au
###stop editing

host=`hostname -f`
if (( $(ps -ef | grep -v grep | grep $service | wc -l) > 0 ))
then
 echo "$service is running"
else
 /root/.nvm/versions/node/v4.4.5/bin/swagger project start -m /root/snpts/my-mock-api &
 if (( $(ps -ef | grep -v grep | grep $service | wc -l) > 0 ))
 then
  subject="$service at $host has been started"
  echo "$service at $host wasn't running and has been started" | mail -s "$subject" $email
 else
  subject="$service at $host is not running"
  echo "$service at $host is stopped and cannot be started!!!" | mail -s "$subject" $email
 fi
fi

Ref: http://www.akamaras.com/linux/linux-script-to-check-if-a-service-is-running-and-start-it-if-its-stopped/