0

I'm struggling to create a bash script that monitors the web service and if is down to restart the service in a while loop until it comes back up with a 200 status response.

Example :

#!/bin/bash
HTTPD=`curl -A "Web Check" -sL --connect-timeout 3 -w "%{http_code}\n" "http://127.0.0.1" -o /dev/null`
until [ "$HTTPD" == "200" ]; do
    printf '.'
    sleep 5
    service nginx restart
done

or

while [ "$HTTPD" != "200" ];
do
   service nginx restart
   sleep 5
   if [ "$HTTPD" == "200" ];then
        break;
   else
        service nginx restart
   fi
done

Both of them are working like 80% , the problem is that the loop will not re-check the status of $HTTPD response and break the loop.

I could add HTTPD=200; after restart line , but I want the script to check for the real status response.

EDIT: Working version

#!/bin/bash

HTTPD=`curl -A "Web Check" -sL --connect-timeout 3 -w "%{http_code}\n" "http://127.0.0.1" -o /dev/null`
until [ "$HTTPD" == "200" ]; do
    printf '.'
    sleep 3
    service nginx restart
    HTTPD=`curl -A "Web Check" -sL --connect-timeout 3 -w "%{http_code}\n" "http://127.0.0.1" -o /dev/null`
done
  • I don't know why this question is down-voted multiple times, but I want to say thank you for providing the EDIT: Working version -- it helped me. I hope you have a great day. Thank you. – Greg Edwards Dec 22 '17 at 14:31
1

Don't reinvent the wheel. Plenty of tools do this already. Also, you check the status of the web server exactly once at the startup of the script (the curl command doesn't get executed every time you reference the $HTTP variable, but only once when you initially define the variable. You would need to add the HTTP=\curl` line into the loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.