BASH
Checking Web Service Health Status
A bash script to perform a quick HTTP health check on a given URL, returning its status code to verify service availability and responsiveness.
#!/bin/bash
# Function to check HTTP status code of a URL
# Usage: check_health <URL>
check_health() {
local URL="$1"
if [ -z "$URL" ]; then
echo "Error: No URL provided." >&2
return 1
fi
echo "Checking health for: $URL"
HTTP_STATUS=$(curl -o /dev/null -s -w '%{http_code}' "$URL")
if [ "$HTTP_STATUS" -eq 200 ]; then
echo "Success: $URL is UP (HTTP $HTTP_STATUS)"
return 0
else
echo "Failure: $URL is DOWN (HTTP $HTTP_STATUS)" >&2
return 1
fi
}
# Example usage:
# check_health "https://www.google.com"
# check_health "http://localhost:3000/health"
# To make it runnable directly with an argument:
if [ -n "$1" ]; then
check_health "$1"
else
echo "Usage: $0 <URL>"
exit 1
fi
How it works: This bash function uses `curl` to perform a non-intrusive HTTP GET request to a specified URL. It discards the response body (`-o /dev/null`) and only prints the HTTP status code (`-w '%{http_code}'`). The script then checks if the status code is 200 (OK) to determine if the web service is healthy and reachable, providing a clear indication of its operational status.