Home > Back-end >  How to write a shell script to check the service file is running or not if not then restart the serv
How to write a shell script to check the service file is running or not if not then restart the serv

Time:09-16

I have written one shell script to check the status of a service file, if I run that script I'm getting an error.

#! /bin/sh
SERVICE = myApp

while(true)
do
   if ! ps -ef | grep -i $SERVICE > /dev/null
       then nohup /full_path/runMyApp & 
   fi
   sleep 10
done

here I'm getting error as follows:

try grep [OPTION]... pattern[FILE]... nohup:failed to run command 'full_path/runMyApp':no such file or directory

CodePudding user response:

Your grep command fails, and myApp isn't found in the path you give.

Problems/fixes in your script:

  1. Don't put a space between #! and /bin/sh.
  2. You must not have spaces around the = sign when you assign a variable (this causes your grep to fail).
  3. The variable should be quoted in the grep command, in case the name has a space.
  4. Make sure there is a / before and after the path to myApp. It looks like you might have missed the trailing / above.
  5. When grepping for a process (not the best way to check if a process is running), make sure you exclude the grep process itself, otherwise you'll always see some process running and think your service is up.
  6. The parenthesis in while isn't needed, as this isn't C. In sh, it means you run the command true in a subshell.
  7. grep has a parameter -q which makes it output nothing. This is better than redirecting to /dev/null.

Putting it all together:

#!/bin/sh
SERVICE="myApp"

while true
do
   if ! ps -ef | grep -v grep | grep -qi "$SERVICE"
       then nohup "/full_path/$SERVICE" & 
   fi
   sleep 10
done
  • Related