简体   繁体   中英

Check wget response for both status code and content

I am writing a healthcheck script for docker container using bash. It's supposed to check both URL returning status 200 and its content.

Is there a way to use wget to check that URL returns 200 AND that URLs content contains a certain word (in my case that word is "DB_OK") while preferably calling it only once?

StatusString=$(wget -qO- localhost:1337/status)

#does not work
function available_check(){
  if [[ $StatusString != *"HTTP/1.1 200"* ]];
      then AvailableCheck=1
      echo "availability check failed"
  fi
}

#checks that statusString contains "DB_OK", works
function db_check(){
  if [[ $StatusString != *"DB_OK"* ]];
      then DBCheck=1
      echo "db check failed"
  fi
}
#!/bin/bash

# -q removed, 2>&1 added to get header and content
StatusString=$(wget -O- 'localhost:1337/status' 2>&1)

function available_check{
  if [[ $StatusString == *"HTTP request sent, awaiting response... 200 OK"* ]]; then
    echo "availability check okay"
  else
    echo "availability check failed"
    return 1
  fi
}

function db_check{
  if [[ $StatusString == *"DB_OK"* ]]; then
    echo "content check okay"
  else
    echo "content check failed"
    return 1
  fi
}

if available_check && db_check; then
  echo "everything okay"
else
  echo "something failed"
fi

Output:

availability check okay
content check okay
everything okay

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM