0

I would like to restart the apache server, when it's down. Hence I wrote a script below using curl and an if loop

curl example.com
si='curl example.com'
if test si !=0
then
service apache2 restart
fi
~

I expect to restart apache server, if the site is down

But It returns the following error

curl: (7) Failed to connect to example.com port 80: Connection refused

autostart.sh: line 8: test: si: unary operator expected

2

curl seem to wait forever by default if the server doesn't respond, so if you must use curl, use it together with --max-time parameter. 1 line of script is enough to get this task done:

curl --max-time 15 example.com || sudo service apache2 restart 

assuming vahaitech.com is your site, if curl doesn't finish downloading it in 15 seconds, then restart the apache2 service.

  • you used or condition , if curl returns error , the second will executed, otherwise curl only.May i correct – SuperKrish Dec 2 '16 at 9:36
2

I think your looking for the previous command exit status flag, for example;

#!/bin/bash

curl example.com
if (( $? > 0 )); then
    sudo service apache2  restart
fi

This will look at the curls exit status, and if it's anything but 0 it will restart the apache2 server

If you want to suppress the output of these commands so it doesn't say anything, be sure to add

&>/dev/null

After each command

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.