BASH

Monitor Web Service Health Check

Bash script to perform a basic health check on a web service by curling a URL and verifying the HTTP status code and optionally checking for expected content.

#!/bin/bash

# Usage: ./check_health.sh <url> <expected_status_code> [expected_content_string]

URL=$1
EXPECTED_STATUS=$2
EXPECTED_CONTENT=$3

if [ -z "$URL" ] || [ -z "$EXPECTED_STATUS" ]; then
  echo "Usage: $0 <url> <expected_status_code> [expected_content_string]"
  echo "Example: $0 http://localhost:3000/health 200 'OK'"
  exit 1
fi

echo "Checking health of $URL..."

# Fetch status code and content
HTTP_STATUS=$(curl -s -o /tmp/health_check_output.txt -w "%\{http_code\}" "$URL")
CONTENT=$(cat /tmp/health_check_output.txt)

SUCCESS=true

if [ "$HTTP_STATUS" -ne "$EXPECTED_STATUS" ]; then
  echo "ERROR: Unexpected HTTP status code. Expected $EXPECTED_STATUS, got $HTTP_STATUS."
  SUCCESS=false
fi

if [ -n "$EXPECTED_CONTENT" ]; then
  if ! echo "$CONTENT" | grep -q "$EXPECTED_CONTENT"; then
    echo "ERROR: Expected content '$EXPECTED_CONTENT' not found in response."
    SUCCESS=false
  else
    echo "Content check passed: '$EXPECTED_CONTENT' found."
  fi
fi

if $SUCCESS; then
  echo "Health check PASSED for $URL."
  rm /tmp/health_check_output.txt # Clean up temp file
  exit 0
else
  echo "Health check FAILED for $URL."
  rm /tmp/health_check_output.txt # Clean up temp file
  exit 1
fi
How it works: This script uses `curl` to make an HTTP request to a specified URL, capturing both the HTTP status code and the response body. It then compares the actual status code against an `EXPECTED_STATUS` and optionally checks if the response body contains a specific `EXPECTED_CONTENT_STRING` using `grep`. It provides clear pass/fail messages, making it ideal for basic uptime monitoring, integration tests in CI/CD pipelines, or quick server health verification for web services.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs