BASH

Check Website Availability with HTTP Status Codes

A simple bash script to verify the availability and health of a website by checking its HTTP status code, useful for monitoring and automated health checks.

#!/bin/bash
# Script to check website HTTP status and report its availability

# Configuration
URL="https://example.com"       # The URL of the website to check
EXPECTED_STATUS="200"           # The expected HTTP status code for success (e.g., 200, 301, 302)
TIMEOUT_SECONDS=5               # Timeout for the curl request in seconds

echo "Checking website availability for: $URL"

# Use curl to get the HTTP status code
# -s: Silent mode, hides progress meter and error messages
# -o /dev/null: Discard the body of the response
# -w "%{{http_code}}": Output only the HTTP status code
# --connect-timeout: Limit the time curl spends trying to connect
HTTP_STATUS=$(curl -s -o /dev/null -w "%{{http_code}}" --connect-timeout "$TIMEOUT_SECONDS" "$URL")

# Compare the returned status with the expected status
if [ "$HTTP_STATUS" -eq "$EXPECTED_STATUS" ]; then
    echo "Success: Website $URL is UP! Status: $HTTP_STATUS"
    exit 0 # Indicate success
else
    echo "Warning: Website $URL is DOWN or returned unexpected status: $HTTP_STATUS (Expected: $EXPECTED_STATUS)"
    exit 1 # Indicate failure
fi
How it works: This script uses `curl` to perform a non-intrusive check on a website's availability. It fetches only the HTTP status code and discards the response body, making it fast and efficient. The script then compares the received status code against an `EXPECTED_STATUS` (typically 200 for OK) and reports whether the site is up or down. This is invaluable for basic uptime monitoring or as part of a larger health check system.

Need help integrating this into your project?

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

Hire DigitalCodeLabs