How Do I Write a Shell Script for Checking Website Live or Not

I am writing a shell script to monitor website live or not and send an email alert below is my code

#!/bin/bash
if [[ curl -s --head  --request GET  | grep "200 OK" > /dev/null] && [ curl -s --head --request GET  | grep "200 OK" > /dev/null ]]
then echo "The HTTP server on opx.com and oss.com is up!" #> /dev/null
else
msg="The HTTP server  opx.com Or oss.com is down "
email=""

curl --data "body=$msg &to=$email &subject=$msg" 
fi;

if i run this code i got

./Monitoring_Opx_Oss: line 2: conditional binary operator expected
./Monitoring_Opx_Oss: line 2: syntax error near `-s'
./Monitoring_Opx_Oss: line 2: `if [[ curl -s --head  --request GET  | grep "200 OK" > /dev/null] && [ curl -s --head --request GET  | grep "200 OK" > /dev/null ]] '

Please correct me...

1 Answer

Change it do this:

if [ $(curl -s --head  --request GET  | grep "200 OK" > /dev/null) ] && [ $(curl -s --head --request GET  | grep "200 OK" > /dev/null) ]

To check the status of a command inside an if, you have to do it like

if [ $(command) ]

while you were using

if [ command]

note also the need of spaces around [ ]: if [_space_ command _space_ ]

Update

Based on Ansgar Wiechers's comment, you can also use the following:

if curl -s --head  --request GET  | grep "200 OK" > /dev/null && curl -s --head --request GET  | grep "200 OK" > /dev/null;

That is,

if command && command
3

Your Answer

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

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.

Share this article
Twitter Facebook Pinterest