Search code examples
batch-filecurlcmdfindstr

How can I make this online site checker work?


I'm creating an online site checker (tells you if it's up or down) with CURL on Windows but it doesn't seem to work.

I've tried creating a simple script on Windows. First, I check Google with curl and output redirection in statusgoogle.txt file. Then, I ask findstr to find the sentence "Connection established". That means the website is UP. Error code 0 for findstr means it found what it was looking for. So, if it found what it was looking for, I get a message "site is up". If it doesn't find, I get a different error code, so that the message should be "site down".

The problem is: I get both messages. I already tried using if %errorlevel%, but it didn't work too.

Also, I'd like a code with multiple websites because I'm creating a bat script that actually checks about 9 or 10 website at once.

curl -i http://www.google.com/ 1> statusgoogle.txt
findstr /c:"Connection established" statusgoogle.txt
if errorlevel 0 (GOTO :upwarning) else (GOTO :downwarning)
:upwarning
echo site up
:downwarning
echo site down

If findstr find the string "Connection established", then I should expect a message with "site up". What it is actually happening is this: it shows both messages "site up" and "site down".


Solution

  • One of the misunderstandings of the classic if errorlevel 0 command,
    which translates to (see help if)

    if errorlevel is 0 or greater
    

    which is always true for positive errorlevels.

    Either

    • check if errorlevel 1 and reverse the logic
      if errorlevel 1 (GOTO :downwarning) else (GOTO :upwarning)
    • check for the current value of %errorlevel%
      if %errorlevel%==0 (GOTO :upwarning) else (GOTO :downwarning)
    • use conditional execution on success/fail &&/||

    curl -i http://www.google.com/ 1> statusgoogle.txt
    findstr /c:"Connection established" statusgoogle.txt &&(GOTO :upwarning)||(GOTO :downwarning)
    
    :upwarning
    echo site up
    goto :eof
    
    :downwarning
    echo site down