Home > Mobile >  Bash script to test website status, then run command
Bash script to test website status, then run command

Time:05-14

I am trying to write a very basic bash script, to run on a linux server. I am not sure why it's not working.

The intention is to test if a website returns a 200 OK response. If it does, then exit. If it does not, then run a command.

The script is:

#!/bin/bash

if HEAD https://google.com | grep '200\ OK' | wc -l;  then
   echo "Site is up";
else
   sudo wo clean --all && sudo wo stack reload --all
fi

The issue is that if the site is up, it gives the expect output. Namely ...

1
Site is up

But if the site is down (say I replace https://google.com with https://766google.com, the output I get is:

0
Site is up

I've tried numerous variations, including put the HEAD ... command in [ ].

For example, I tried this:

#!/bin/bash

if [ HEAD https://google.com | grep '200\ OK' | wc -l ];  then
   echo "Site is up";
else
   sudo wo clean --all && sudo wo stack reload --all
fi

But then when the site is down, it runs the desired command, but gives an error ... I get this output:

./sitecheck.sh: line 3: [: missing `]'
wc: ]: No such file or directory
Cleaning NGINX FastCGI cache ... 
[THE OUTPUT OF COMMAND IT RUNS WHEN SITE IS DOWN]

Would someone please explain what is wrong with this script?

Thanks.

CodePudding user response:

If you want to count the number of lines of output, you need to capture the pipeline's output with $(...), and then use ((...)) to do an arithmetic comparison. One set of parentheses is output capturing; two sets is arithmetic.

if (($(HEAD https://google.com | grep '200 OK' | wc -l) > 0)); then
   echo "Site is up";
else
   sudo wo clean --all && sudo wo stack reload --all
fi

A simpler way to do this is to use grep -q. Instead of outputting matches, requiring you to parse grep's output, grep -q directly returns a success or failure exit code indicating whether it found a match.

if HEAD https://google.com | grep -q '200 OK'; then
   echo "Site is up";
else
   sudo wo clean --all && sudo wo stack reload --all
fi
  •  Tags:  
  • bash
  • Related