BASH
Basic Web Service Endpoint Health Check
Perform a quick health check on a web service or API endpoint using `curl` in a bash script, verifying its HTTP status code for responsiveness.
#!/bin/bash
# --- Configuration ---
SERVICE_URL="http://localhost:3000/health" # IMPORTANT: Update to your service URL
EXPECTED_STATUS=200 # The HTTP status code you expect for a healthy service
TIMEOUT_SECONDS=5 # Timeout for the curl request
# --- Script Start ---
echo "Performing health check on: $SERVICE_URL"
# Use curl to get only the HTTP status code
# -s: Silent mode, don't show progress or error messages
# -o /dev/null: Discard output (body of the response)
# -w "%"{http_code}": Print only the HTTP status code
# --max-time: Set a maximum time for the operation
HTTP_STATUS=$(curl -s -o /dev/null -w "%"{http_code}"" --max-time "$TIMEOUT_SECONDS" "$SERVICE_URL")
CURL_EXIT_CODE=$?
if [ "$CURL_EXIT_CODE" -ne 0 ]; then
echo "ERROR: Curl failed with exit code $CURL_EXIT_CODE. Network issue or service unreachable."
exit 1
fi
echo "Received HTTP Status: $HTTP_STATUS"
if [ "$HTTP_STATUS" -eq "$EXPECTED_STATUS" ]; then
echo "SUCCESS: Service at $SERVICE_URL is healthy (Status $HTTP_STATUS)."
exit 0
else
echo "FAILURE: Service at $SERVICE_URL returned unexpected status $HTTP_STATUS (Expected $EXPECTED_STATUS)."
exit 1
fi
How it works: This script provides a simple yet effective way to check the health of a web service endpoint. It uses `curl` to send a request to a specified URL, discards the response body, and extracts only the HTTP status code. The script then compares this status code against an expected value (e.g., 200 OK) to determine if the service is considered healthy. This is ideal for quick diagnostics or as a step in a CI/CD pipeline.