BASH
Check Website Uptime and HTTP Status
A robust Bash script to perform a health check on a given URL, reporting its HTTP status code and response time, essential for monitoring web services.
#!/bin/bash
# Usage: check_url_status.sh <URL>
# Example: check_url_status.sh https://www.example.com
if [ -z "$1" ]; then
echo "Usage: $0 <URL>"
echo "Example: $0 https://api.myservice.com/health"
exit 1
fi
URL="$1"
echo "Checking URL: $URL"
# Use curl to get HTTP status code and response time
# -s: Silent mode
# -o /dev/null: Discard output (body)
# -w: Format output (http_code, time_total)
RESPONSE=$(curl -s -o /dev/null -w '%{http_code}:%{time_total}
' "$URL")
HTTP_STATUS=$(echo "$RESPONSE" | cut -d':' -f1)
RESPONSE_TIME=$(echo "$RESPONSE" | cut -d':' -f2)
if [ "$HTTP_STATUS" -eq 200 ]; then
echo "Status: OK (HTTP $HTTP_STATUS)"
echo "Response Time: ${RESPONSE_TIME}s"
exit 0
elif [ "$HTTP_STATUS" -eq 000 ]; then
echo "Status: FAILED (Could not connect or resolve host)"
echo "Response Time: ${RESPONSE_TIME}s"
exit 1
else
echo "Status: FAILED (HTTP $HTTP_STATUS)"
echo "Response Time: ${RESPONSE_TIME}s"
exit 1
fi
How it works: This script provides a simple yet effective way to check the availability and responsiveness of a web application or API endpoint. It uses `curl` to send an HTTP request to the specified URL, captures the HTTP status code (e.g., 200 for success, 404 for not found, 500 for server error), and records the total time taken for the request. This is a fundamental tool for web developers to quickly diagnose connectivity issues or monitor service health.