Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a process is running and if not, restart it using Cron

I have created restart.sh with followin code

#!/bin/bash
ps -aux | grep sidekiq > /dev/null
if [ $? -eq 0 ]; then
  echo "Process is running."
else
  echo "Process is not running."
fi

To check if sidekiq process is running or not. I will put this script in cron to run daily so if sidekiq is not running, it will start automatically.

My problem is, with

ps -aux | grep sidekiq

even when the process is not running, it shows

myname 27906  0.0  0.0  10432   668 pts/0    S+   22:48   0:00 grep --color=auto sidekiq

instead of nothing. This gets counted in grep hence even when the process is not running, it shows as "sidekiq" process is running. How to not count this result ? I believe I have to use awk but I am not sure how to use it here for better filtering.

like image 603
iCyborg Avatar asked Dec 07 '16 17:12

iCyborg


1 Answers

To exclude the grep result from the ps output. Do

ps -aux | grep -v grep | grep sidekiq

(or) do a regEx search of the process name, i.e. s followed by rest of the process name.

ps -aux | grep [s]idekiq

To avoid such conflicts in the search use process grep pgrep directly with the process name

pgrep sidekiq

An efficient way to use pgrep would be something like below.

if pgrep sidekiq >/dev/null
then
     echo "Process is running."
else
     echo "Process is not running."
fi
like image 120
Inian Avatar answered Sep 20 '22 12:09

Inian