← Back to all snippets
BASH

Simple HTTP URL Health Check

Perform a quick health check on any HTTP/HTTPS URL using curl in Bash, verifying response status and connectivity for web services.

#!/bin/bash

# Default URL
URL=""

# Parse arguments
while [[ "$#" -gt 0 ]]; do
    case "$1" in
        -u|--url) URL="$2"; shift ;;
        *) echo "Unknown parameter passed: $1"; exit 1 ;;
    esac
    shift
done

if [ -z "$URL" ]; then
    echo "Usage: $0 -u <URL>"
    echo "Example: $0 -u https://www.google.com"
    exit 1
fi

echo "Checking health of: $URL"

# Use curl to get HTTP status code
HTTP_STATUS=$(curl -s -o /dev/null -w "%{http_code}" "$URL")

if [ "$HTTP_STATUS" -ge 200 ] && [ "$HTTP_STATUS" -lt 300 ]; then
    echo "Health check PASSED: $URL returned HTTP status $HTTP_STATUS"
    exit 0
else
    echo "Health check FAILED: $URL returned HTTP status $HTTP_STATUS"
    exit 1
fi
How it works: This script performs a basic health check for a given URL using `curl`. It extracts the HTTP status code and checks if it falls within the successful range (2xx). The script requires a URL as an argument (`-u` or `--url`) and exits with a status of 0 for success or 1 for failure, making it suitable for simple checks in CI/CD pipelines, pre-deployment verification, or quick troubleshooting of web services without implementing complex monitoring systems.

Need help integrating this into your project?

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

Hire DigitalCodeLabs