Reputation: 53
I want to create script that will check continuously process status running or not. If process will not run, script should catch it and restart it in a seconds. How can I run continuously this script on the system and how should I change the script via ---> Important points: it should take as parameters these: 1-seconds to wait between attempts to restart service, 2- number of attempts and 3- generate logs of events. Nginx is a example for the process. It can be replaceable.
#!/bin/bash
SERVICE="nginx"
if pgrep -x "$SERVICE" >/dev/null
then
echo "$SERVICE is running"
else
echo "$SERVICE stopped"
# start nginx if stopped
echo "$SERVICE starting"
systemctl start $SERVICE
fi
Upvotes: 0
Views: 712
Reputation: 16950
You can try something like this:
#!/bin/bash
service="nginx"
seconds=2
retries=3
until (( retries-- == 0 ))
do
property=$(systemctl show --property MainPID "$service")
if [[ $property == MainPID=0 ]]
then
echo "$service stopped"
echo "$service starting"
systemctl start "$service" >& /dev/null
else
echo "$service is running"
exit
fi
sleep "$seconds"
done
echo "$service is broken"
Upvotes: 3