1

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

Ari
  • 130
  • 1
  • 9
SuperKrish
  • 775
  • 1
  • 12
  • 22
  • did you check this post ? http://unix.stackexchange.com/questions/84814/health-check-of-web-page-using-curl – Kamaraj Dec 02 '16 at 08:32

2 Answers2

3

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.

SuperKrish
  • 775
  • 1
  • 12
  • 22
SparedWhisle
  • 3,588
  • 4
  • 22
  • 35
  • you used or condition , if curl returns error , the second will executed, otherwise curl only.May i correct – SuperKrish Dec 02 '16 at 09: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

enconn
  • 183
  • 1
  • 1
  • 6