BASH

HTTP Service Health Check Script

A bash script to perform a basic HTTP health check on a web service, useful for monitoring, deployment validation, and automated checks.

#!/bin/bash

# Default values
URL="http://localhost:80"
EXPECTED_STATUS=200
TIMEOUT=5 # seconds

# Usage function
usage() {
  echo "Usage: $0 [-u <url>] [-s <expected_status>] [-t <timeout>]"
  echo "  -u: URL to check. Default: $URL"
  echo "  -s: Expected HTTP status code. Default: $EXPECTED_STATUS"
  echo "  -t: Connection timeout in seconds. Default: $TIMEOUT"
  exit 1
}

# Parse options
while getopts "u:s:t:" opt; do
  case "${opt}" in
    u)
      URL=${OPTARG}
      ;;
    s)
      EXPECTED_STATUS=${OPTARG}
      ;;
    t)
      TIMEOUT=${OPTARG}
      ;;
    *)
      usage
      ;;
  esac
done

echo "Checking URL: $URL"
echo "Expecting HTTP Status: $EXPECTED_STATUS"
echo "Timeout: ${TIMEOUT}s"

# Perform the HTTP request and capture status code
HTTP_CODE=$(curl -s -o /dev/null -w "%{\http_code}" --connect-timeout "$TIMEOUT" "$URL")

if [ $? -ne 0 ]; then
  echo "Error: Failed to connect to $URL within $TIMEOUT seconds."
  exit 1
fi

echo "Received HTTP Status: $HTTP_CODE"

if [ "$HTTP_CODE" -eq "$EXPECTED_STATUS" ]; then
  echo "SUCCESS: $URL returned the expected status $EXPECTED_STATUS."
  exit 0
else
  echo "FAILURE: $URL returned $HTTP_CODE, expected $EXPECTED_STATUS."
  exit 1
fi
How it works: This script provides a flexible way to check the health or uptime of a web service by performing an HTTP request. It uses `curl` to fetch the URL, extracting only the HTTP status code. The script allows customization of the target URL, expected status code, and connection timeout via command-line arguments using `getopts`. It reports success if the received status matches the expectation, otherwise, it reports a failure, making it ideal for CI/CD pipelines, cron-based monitoring, or simple service validation.

Need help integrating this into your project?

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

Hire DigitalCodeLabs