BASH

Monitor Website Availability and Status Code

Script to periodically check your website's availability and HTTP status code using `curl`, useful for simple uptime monitoring and health checks.

#!/bin/bash

# Configuration
URL="https://yourwebsite.com"
EXPECTED_STATUS=200

# Get HTTP status code
# -o /dev/null: discard output
# -s: silent mode
# -w "%{http_code}
": write only the HTTP status code
STATUS_CODE=$(curl -o /dev/null -s -w "%{http_code}
" "$URL")

# Check if the status code matches the expected one
if [ "$STATUS_CODE" -eq "$EXPECTED_STATUS" ]; then
  echo "$(date '+%Y-%m-%d %H:%M:%S') - $URL is UP (Status: $STATUS_CODE)"
else
  echo "$(date '+%Y-%m-%d %H:%M:%S') - $URL is DOWN or returned an error (Status: $STATUS_CODE)" >&2 # Output error to stderr
  exit 1
fi
How it works: This script uses `curl` to perform a health check on a specified URL. It retrieves only the HTTP status code (`-w "%{http_code} "`) without downloading the page content (`-o /dev/null -s`). The script then compares the received status code against an `EXPECTED_STATUS` (defaulting to 200 for OK). It logs the status with a timestamp, indicating whether the website is 'UP' or 'DOWN', and exits with a non-zero status if an error occurs, useful for integration with 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