BASH

Perform a Basic HTTP Endpoint Health Check

A bash script designed to perform a basic HTTP endpoint health check using curl, verifying the HTTP status code for robust service monitoring and quick issue detection in web apps.

#!/bin/bash

# Perform a basic HTTP health check on a given URL.
# Usage: ./health_check.sh "http://localhost:3000/health" [expected_status_code]

URL="$1"
EXPECTED_STATUS=${2:-200} # Default to 200 OK if not provided

if [ -z "$URL" ]; then
  echo "Usage: $0 <URL> [expected_status_code]"
  exit 1
fi

# Use curl to get only the HTTP status code, discarding body and headers
HTTP_STATUS=$(curl -s -o /dev/null -w "%{\http_code}" "$URL")

if [ "$HTTP_STATUS" -eq "$EXPECTED_STATUS" ]; then
  echo "Health check PASSED for $URL. Status: $HTTP_STATUS"
  exit 0
else
  echo "Health check FAILED for $URL. Expected $EXPECTED_STATUS, got $HTTP_STATUS"
  exit 1
fi
How it works: This script performs an HTTP GET request to a specified URL using `curl`, extracting only the HTTP status code from the response. It then compares this status code against an optional expected value (defaulting to 200 OK). This tool is highly useful for rapidly checking the availability and correct behavior of web services, APIs, or any HTTP endpoint, providing immediate feedback on service health in automated scripts or manual checks.

Need help integrating this into your project?

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

Hire DigitalCodeLabs