Checking Website Availability with curl
"Is the website up?" sounds like a yes-or-no question, but a website can fail in many different ways: the server can be switched off, the domain name can stop resolving, the web server can answer with an error page, a proxy can answer with a friendly "maintenance" page that still has status 200, the page can take thirty seconds to load, or the HTTPS certificate can expire and make every browser refuse the site. A useful availability check tests for each of these, and curl can do all of it from a Bash script.
curl is a command-line tool that transfers data to and from URLs. It is installed on almost every Linux system, on macOS and on Windows 10 and later. For monitoring, three of its features matter most: it can report the HTTP status code and timing details, it returns a precise exit status that says why a request failed, and it can enforce time limits so a hung server cannot hang the script.
The examples in this lesson use a small test web server on the local machine, reached as shop.test (an entry in /etc/hosts points that name to 127.0.0.1; the .test domain is reserved for testing). It serves a home page, a health endpoint, an error page, a redirect, a slow page and a few other cases, over HTTP on port 8080 and HTTPS on port 8443.
Understanding an HTTP Check
When curl fetches a URL, several steps happen in order, and each can fail separately:
- Name resolution: the host name (
shop.test) is looked up in DNS (or/etc/hosts) to get an IP address. - Connection: a TCP connection is opened to that address and port.
- TLS handshake (HTTPS only): the server presents its certificate, and
curlchecks that it is valid, trusted and issued for that host name. - Request and response:
curlsends the request; the server answers with a status code, headers and a body.
The status code is a three-digit number grouped by its first digit:
| Range | Meaning | Examples |
|---|---|---|
| 2xx | success | 200 OK, 204 No Content |
| 3xx | redirection, the content is elsewhere | 301 Moved Permanently, 302 Found |
| 4xx | client error, the request was wrong | 404 Not Found, 401 Unauthorized, 429 Too Many Requests |
| 5xx | server error | 500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable |
A failure in steps 1 to 3 means curl never received an answer; a failure in step 4 means the server answered, but not with what you expected. A good check distinguishes the two.
Fetching a Page
Without options, curl prints the response body to standard output. When the output goes to a terminal it prints only the body; when standard output is not a terminal (for example in a script whose output is captured), it also prints a progress meter on standard error:
curl http://shop.test:8080/
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0100 61 100 61 0 0 47470 0 --:--:-- --:--:-- --:--:-- 61000
<html><title>Shop</title><h1>Welcome to the Shop</h1></html>
-s (--silent) removes the progress meter, but it also removes error messages. -S (--show-error) brings the error messages back. -sS is the usual combination for scripts: quiet when it works, a clear message when it fails.
curl -s http://shop.test:8080/
<html><title>Shop</title><h1>Welcome to the Shop</h1></html>
Getting the Status Code
-o FILE (--output) writes the body to a file instead of the screen; -o /dev/null discards it. -w FORMAT (--write-out) prints information about the transfer after it finishes. The variable %{http_code} is the status code:
curl -s -o /dev/null -w '%{http_code}\n' http://shop.test:8080/
curl -s -o /dev/null -w '%{http_code}\n' http://shop.test:8080/error
200
500
An error page is still a successful transfer
By default, curl considers any HTTP answer a success, even a 500 error page, because the transfer itself worked:
curl -s -o /dev/null http://shop.test:8080/error; echo "exit $?"
exit 0
--fail (-f) changes this: when the server answers with 400 or higher, curl prints an error and exits with status 22:
curl -sS -o /dev/null --fail http://shop.test:8080/error; echo "exit $?"
curl: (22) The requested URL returned error: 500
exit 22
--fail is convenient when "any status below 400" is good enough. A monitoring script usually wants the exact code instead, so it can check for a specific value, such as a 301 on an old address or a 404 on a page that must stay deleted. Then it is better to read %{http_code} and compare it in Bash.
Headers only
-I (--head) sends a HEAD request, which asks for the headers without the body:
curl -sI http://shop.test:8080/
HTTP/1.0 200 OK
Server: BaseHTTP/0.6 Python/3.13.18
Date: Tue, 24 Nov 2026 15:07:08 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 61
HEAD is lighter, but some applications handle HEAD differently from GET, or not at all. A check that should match what visitors see uses a normal GET request and discards the body.
Redirects
A redirect is a 3xx answer with a Location header pointing elsewhere. By default curl does not follow it; %{redirect_url} shows where it points. -L (--location) follows redirects, and %{num_redirects} and %{url_effective} show how many were followed and where the request ended:
curl -s -o /dev/null -w '%{http_code} -> %{redirect_url}\n' http://shop.test:8080/old
curl -sL -o /dev/null -w '%{http_code} after %{num_redirects} redirect(s): %{url_effective}\n' http://shop.test:8080/old
301 -> http://shop.test:8080/
200 after 1 redirect(s): http://shop.test:8080/
Which one to use depends on the question. "Does the old address still redirect?" needs the first form. "Does a visitor eventually reach a working page?" needs -L.
Exit Status: Why a Request Failed
When curl cannot get an answer at all, its exit status says why. The status code is then reported as 000:
curl -sS -o /dev/null http://shop.test:9999/; echo "exit $?"
curl -s -o /dev/null -w '%{http_code}\n' http://shop.test:9999/; echo "exit $?"
curl -sS -o /dev/null http://no-such-host.invalid/; echo "exit $?"
curl -sS -o /dev/null --max-time 2 http://shop.test:8080/slow; echo "exit $?"
curl: (7) Failed to connect to shop.test port 9999 after 0 ms: Couldn't connect to server
exit 7
000
exit 7
curl: (6) Could not resolve host: no-such-host.invalid
exit 6
curl: (28) Operation timed out after 2002 milliseconds with 0 bytes received
exit 28
The most common exit statuses in availability checks:
| Exit | Meaning | Typical cause |
|---|---|---|
| 0 | the transfer worked (any HTTP status without --fail) | |
| 6 | could not resolve host | wrong name, DNS outage, expired domain |
| 7 | could not connect | server or service down, firewall, wrong port |
| 22 | HTTP status 400 or higher, with --fail | error page |
| 28 | operation timed out | overloaded or hung server, network problem |
| 35 | TLS handshake failed | protocol or cipher mismatch |
| 52 | empty reply from server | server closed the connection without answering |
| 56 | failure receiving data | connection reset during the transfer |
| 60 | certificate could not be verified | expired, self-signed, wrong host name or missing intermediate certificate |
The man curl page lists all of them under "EXIT CODES".
Time Limits
Without limits, curl can wait for a very long time on a server that accepts the connection but never answers. Every check in a script needs limits:
--connect-timeout SECONDSlimits only the connection phase (name resolution, TCP connect and TLS handshake).--max-time SECONDS(-m) limits the whole operation, including the download. When it expires,curlstops and exits with 28, as shown above with a page that takes 4 seconds to answer.
Both accept decimals, such as --max-time 2.5. A typical check uses a short connect timeout (a few seconds) and a somewhat longer total limit.
Measuring Response Time
-w provides timing variables, each measured in seconds from the start of the request:
curl -s -o /dev/null --cacert cert.pem \
-w 'dns %{time_namelookup} connect %{time_connect} tls %{time_appconnect} first byte %{time_starttransfer} total %{time_total}\n' \
https://shop.test:8443/
dns 0.000360 connect 0.000417 tls 0.003438 first byte 0.004049 total 0.004146
| Variable | Time until |
|---|---|
time_namelookup | the host name was resolved |
time_connect | the TCP connection was open |
time_appconnect | the TLS handshake was finished (0 for plain HTTP) |
time_starttransfer | the first byte of the response arrived |
time_total | the whole transfer finished |
The values are cumulative, so the difference between two of them is the duration of a phase. A large gap between time_appconnect and time_starttransfer means the server took long to produce the page (slow application or database), while a slow time_connect points at the network. This local server answers in a few milliseconds; a real website over the internet typically needs tens to hundreds of milliseconds.
HTTPS Certificates
For HTTPS, curl verifies the server's certificate against the trusted certificate authorities (CAs) installed on the system. The test server uses a self-signed certificate, which no CA has signed, so verification fails with exit status 60:
curl -sS -o /dev/null https://shop.test:8443/; echo "exit $?"
curl -sS -o /dev/null --cacert cert.pem https://shop.test:8443/; echo "exit $?"
curl: (60) SSL certificate problem: self-signed certificate
More details here: https://curl.se/docs/sslcerts.html
curl failed to verify the legitimacy of the server and therefore could not
establish a secure connection to it. To learn more about this situation and
how to fix it, please visit the web page mentioned above.
exit 60
exit 0
--cacert FILE tells curl to trust the certificates in FILE, which is the correct way to check an internal service that uses its own CA. The environment variable CURL_CA_BUNDLE does the same for every curl command. Do not use -k (--insecure) in a monitoring script: it turns off verification, so the check would stay green while every browser shows a security warning, which is exactly the failure the check should catch.
A certificate that is valid today can expire next week. openssl can read the certificate a server presents and print its expiry date:
openssl s_client -connect shop.test:8443 -servername shop.test </dev/null 2>/dev/null |
openssl x509 -noout -enddate
notAfter=Dec 14 15:01:58 2026 GMT
s_client opens a TLS connection and prints the server's certificate among other details; -servername sends the host name, which servers that host several sites need to choose the right certificate; </dev/null makes it close the connection immediately instead of waiting for input. openssl x509 -noout -enddate extracts the expiry date, which GNU date -d can convert into seconds for a calculation.
Retrying Transient Failures
A single failed request is not always an outage: a server can be restarting, or a load balancer can briefly answer 503. --retry N makes curl try again up to N more times, waiting --retry-delay SECONDS between attempts. It retries only errors that are likely to be temporary: timeouts and the HTTP statuses 408, 429, 500, 502, 503 and 504. A refused connection is retried only with --retry-connrefused, and --retry-all-errors retries everything.
The test URL /flaky answers 503 twice, then 200, in a repeating cycle. One detail is easy to miss:
curl -sS -o /dev/null --retry 2 --retry-delay 1 http://shop.test:8080/flaky; echo "exit $?"
exit 23
Exit status 23 means "write error". Before a retry, curl truncates the output file to throw away the failed answer, and /dev/null cannot be truncated, so curl gives up (without -s, it prints "curl: Failed to truncate file"). With --retry, write the body to a regular file, for example a temporary file:
tmp=$(mktemp)
curl -sS -o "$tmp" -w "%{http_code}\n" --retry 2 --retry-delay 1 http://shop.test:8080/flaky; echo "exit $?"
rm -f "$tmp"
200
exit 0
%{http_code} and the timing variables describe only the last attempt. Combined with --fail, every failed attempt prints its own error message:
curl -sS -o /dev/null --fail --retry 2 --retry-delay 1 http://shop.test:8080/error; echo "exit $?"
curl: (22) The requested URL returned error: 500
curl: (22) The requested URL returned error: 500
curl: (22) The requested URL returned error: 500
exit 22
Checking the Content
A status of 200 does not prove that the page is right. A misconfigured proxy, an empty template or a maintenance page can all answer 200. Checking that the body contains an expected piece of text catches these cases. Health endpoints of applications often return JSON that says whether dependencies such as the database work; the test server's /health-db-down answers 200 with {"status":"degraded","db":"down"}, which only a content check can detect. grep -F searches for the text literally, so characters such as . or " in it have no special meaning.
A Complete Example: A Website Availability Checker
site-check.sh reads a list of checks from a file. Each line names a URL, the status code it must return and, optionally, text the page must contain. For each URL it reports whether the site is OK, slow, wrong or down, and for HTTPS sites it also warns when the certificate is about to expire.
#!/usr/bin/env bash
#
# site-check.sh - check that websites answer with the expected status and content
#
# Usage: site-check.sh [-t SECONDS] [-r RETRIES] [-s SLOW_MS] [-d DAYS] URL_FILE
# -t SECONDS maximum time for each request (default: 10)
# -r RETRIES extra attempts after a timeout or a 408/429/5xx answer (default: 2)
# -s SLOW_MS warn when a page takes at least this many milliseconds (default: 2000)
# -d DAYS warn when an https certificate expires within DAYS days (default: 14)
#
# URL_FILE has one check per line: URL [EXPECTED_STATUS [TEXT THE PAGE MUST CONTAIN]]
# EXPECTED_STATUS defaults to 200. Blank lines and lines starting with # are ignored.
#
# Exit status: 0 all OK, 1 a warning (slow or certificate expiring soon),
# 2 a site is down or wrong, 3 usage or input error
set -uo pipefail
timeout=10 retries=2 slow_ms=2000 cert_days=14
status=0
die() { echo "${0##*/}: $*" >&2; exit 3; }
usage() { echo "usage: ${0##*/} [-t SECONDS] [-r RETRIES] [-s SLOW_MS] [-d DAYS] URL_FILE" >&2; exit 3; }
raise() { (( $1 > status )) && status=$1; return 0; }
# to_ms 0.014665 -> 14: seconds with a decimal fraction to whole milliseconds
to_ms() {
local whole=${1%%.*} frac=000
[[ $1 == *.* ]] && frac=${1#*.}000
echo $(( 10#$whole * 1000 + 10#${frac:0:3} ))
}
# cert_days_left HOST PORT: print the whole days until the certificate expires
cert_days_left() {
local end
end=$(openssl s_client -connect "$1:$2" -servername "$1" </dev/null 2>/dev/null |
openssl x509 -noout -enddate 2>/dev/null) || return 1
end=$(date -d "${end#notAfter=}" +%s) || return 1
echo $(( (end - $(date +%s)) / 86400 ))
}
# check URL EXPECTED TEXT: run one check and print one result line
check() {
local url=$1 expect=$2 text=$3 out rc code secs ms note result=OK level=0
out=$(curl --silent --show-error --output "$body" \
--write-out '%{http_code} %{time_total}' \
--max-time "$timeout" --connect-timeout 5 \
--retry "$retries" --retry-delay 1 \
--user-agent 'site-check/1.0' -- "$url" 2>"$errors")
rc=$?
read -r code secs <<< "$out"
ms=$(to_ms "${secs:-0}")
if (( rc != 0 )); then
result=DOWN level=2
note=$(head -n 1 "$errors") # e.g. "curl: (7) Failed to connect ..."
elif [[ $code != "$expect" ]]; then
result=FAIL level=2 note="expected status $expect"
elif [[ -n $text ]] && ! grep -qF -- "$text" "$body"; then
result=FAIL level=2 note="page does not contain: $text"
elif (( ms >= slow_ms )); then
result=SLOW level=1 note="slower than ${slow_ms} ms"
fi
# Certificate expiry, only for https sites that answered
if (( rc == 0 )) && [[ $url =~ ^https://([^/:?#]+)(:([0-9]+))? ]]; then
local host=${BASH_REMATCH[1]} port=${BASH_REMATCH[3]:-443} days
if days=$(cert_days_left "$host" "$port"); then
if (( days < cert_days )); then
(( level < 1 )) && result=CERT level=1
note+="${note:+; }certificate expires in $days days"
fi
else
(( level < 1 )) && result=CERT level=1
note+="${note:+; }could not read the certificate"
fi
fi
raise "$level"
printf '%-4s %3s %6s ms %s%s\n' "$result" "$code" "$ms" "$url" "${note:+ ($note)}"
}
while getopts ':t:r:s:d:' opt; do
case $opt in
t) timeout=$OPTARG ;;
r) retries=$OPTARG ;;
s) slow_ms=$OPTARG ;;
d) cert_days=$OPTARG ;;
*) usage ;;
esac
done
shift $(( OPTIND - 1 ))
(( $# == 1 )) || usage
url_file=$1
for n in "$timeout" "$retries" "$slow_ms" "$cert_days"; do
[[ $n =~ ^[0-9]{1,6}$ ]] || die "not a whole number: '$n'"
done
(( 10#$timeout >= 1 )) || die "SECONDS must be at least 1"
[[ -f $url_file && -r $url_file ]] || die "cannot read URL file: $url_file"
command -v curl >/dev/null || die "curl is not installed"
body=$(mktemp) && errors=$(mktemp) || die "cannot create temporary files"
trap 'rm -f -- "$body" "$errors"' EXIT
lineno=0 checked=0
while IFS= read -r line || [[ -n $line ]]; do
(( ++lineno ))
[[ $line =~ ^[[:space:]]*(#|$) ]] && continue
read -r url expect text <<< "$line"
expect=${expect:-200}
if [[ ! $url =~ ^https?:// || ! $expect =~ ^[1-5][0-9][0-9]$ ]]; then
echo "${0##*/}: $url_file line $lineno: invalid check: $line" >&2
raise 3
continue
fi
check "$url" "$expect" "$text"
(( ++checked ))
done < "$url_file"
(( checked > 0 )) || die "no checks found in $url_file"
exit "$status"
How It Works
- The check file. Each line is split by
read -r url expect text: the first word is the URL, the second the expected status, and everything after it, spaces included, is the required text. Comment and blank lines are skipped with one regular expression.|| [[ -n $line ]]also processes a last line that has no newline (lesson 114). A line whose URL does not start withhttp://orhttps://, or whose status is not a three-digit code from 100 to 599, is reported with its line number and makes the final status 3, but the remaining checks still run. - One curl call per URL.
--output "$body"saves the page to a temporary file for the content check, which also lets--retrywork (it cannot truncate/dev/null).--write-outprints the status code and total time, whichreadsplits into two variables. Error messages go to a second temporary file, andhead -n 1keeps only the first line, so a long message such as the one for certificate errors does not fill the report.--max-timeand--connect-timeoutstop hung servers, and--user-agentidentifies the checker in the web server's logs.--ensures that a URL can never be read as an option. - Why redirects are not followed. The script compares the status exactly, so a line can require a 301 for an old address. To check the final page behind a redirect, list the final URL, or add
--locationto thecurlcommand. - Deciding the result. The checks run from most to least serious: a
curlfailure (no answer) isDOWN; a wrong status or missing text isFAIL; a correct but slow answer isSLOW. The time is converted to whole milliseconds byto_ms, using the same string technique ashundredthsin lesson 167, because Bash arithmetic has no decimals. - Certificate expiry. For an
https://URL that answered, a regular expression extracts the host and the optional port (BASH_REMATCH[3], defaulting to 443).cert_days_leftfetches the certificate withopenssl s_client, converts itsnotAfterdate to seconds since 1970 withdate -d, and returns the whole days left. A certificate close to expiry, or one that cannot be read, gives aCERTwarning unless the line already has a worse result; the note is added either way. - Exit status. As in lessons 166 and 167,
raisekeeps the worst level: 0 when everything is fine, 1 for warnings, 2 when any site is down or wrong, 3 for input problems.
Running the Complete Example
sites.txt lists the checks for the healthy parts of the test site:
# URL status text the page must contain
http://shop.test:8080/ 200 Welcome to the Shop
http://shop.test:8080/health 200 "status":"ok"
https://shop.test:8443/ 200 Welcome to the Shop
http://shop.test:8080/old 301
http://api.shop.test:8080/missing 404
The test server's certificate is self-signed, so the runs below set CURL_CA_BUNDLE to the test certificate, the way an internal CA would be configured. The output shows the result, the status code, the response time and the URL:
$ site-check.sh sites.txt
OK 200 2 ms http://shop.test:8080/
OK 200 1 ms http://shop.test:8080/health
OK 200 6 ms https://shop.test:8443/
OK 301 1 ms http://shop.test:8080/old
OK 404 1 ms http://api.shop.test:8080/missing
status 0 (0s)
(The (0s) is the run time measured by the test harness with SECONDS.) The certificate was created to be valid for 20 days, so it passes the default 14-day limit but not a 30-day one:
$ site-check.sh -d 30 sites.txt
OK 200 1 ms http://shop.test:8080/
OK 200 1 ms http://shop.test:8080/health
CERT 200 5 ms https://shop.test:8443/ (certificate expires in 19 days)
OK 301 1 ms http://shop.test:8080/old
OK 404 1 ms http://api.shop.test:8080/missing
status 1 (0s)
problems.txt contains one line for each kind of failure:
http://shop.test:8080/error 200
http://shop.test:8080/maintenance 200 Welcome to the Shop
http://shop.test:8080/health-db-down 200 "db":"ok"
http://shop.test:8080/slow 200
http://shop.test:9999/ 200
http://no-such-host.invalid/ 200
http://shop.test:8080/flaky 200 Welcome to the Shop
With a 3-second time limit:
$ site-check.sh -t 3 problems.txt
FAIL 500 1 ms http://shop.test:8080/error (expected status 200)
FAIL 200 1 ms http://shop.test:8080/maintenance (page does not contain: Welcome to the Shop)
FAIL 200 2 ms http://shop.test:8080/health-db-down (page does not contain: "db":"ok")
DOWN 000 3002 ms http://shop.test:8080/slow (curl: (28) Operation timed out after 3002 milliseconds with 0 bytes received)
DOWN 000 0 ms http://shop.test:9999/ (curl: (7) Failed to connect to shop.test port 9999 after 0 ms: Couldn't connect to server)
DOWN 000 1 ms http://no-such-host.invalid/ (curl: (6) Could not resolve host: no-such-host.invalid)
OK 200 1 ms http://shop.test:8080/flaky
status 2 (17s)
Every failure type is reported differently, and each DOWN line carries curl's own reason. The maintenance page and the degraded health endpoint both answered 200; only the content checks caught them. The run took 17 seconds because the 500 page and the timed-out page were each retried twice, with a one-second pause between attempts. The flaky page answered 503 on its first two attempts and 200 on the third, so the retries hid a short hiccup. The file flaky.txt contains only that line (http://shop.test:8080/flaky 200 Welcome to the Shop). With retries turned off, the same page fails:
$ site-check.sh -r 0 flaky.txt
FAIL 503 1 ms http://shop.test:8080/flaky (expected status 200)
status 2 (0s)
$ site-check.sh flaky.txt
OK 200 1 ms http://shop.test:8080/flaky
status 0 (1s)
A page that answers correctly but slowly is a warning, not a failure (slow.txt contains http://shop.test:8080/slow 200 slow page, and the page takes 4 seconds):
$ site-check.sh slow.txt
SLOW 200 4001 ms http://shop.test:8080/slow (slower than 2000 ms)
status 1 (4s)
Without the test certificate in CURL_CA_BUNDLE, the HTTPS site in tls.txt (https://shop.test:8443/health 200) is reported as down, exactly as a visitor's browser would refuse it:
$ site-check.sh tls.txt
DOWN 000 21 ms https://shop.test:8443/health (curl: (60) SSL certificate problem: self-signed certificate)
status 2 (0s)
Mistakes in the check file and invalid options are reported with status 3; valid lines in the same file are still checked. bad.txt contains a comment, a URL without http://, a line with OK instead of a status code, and a valid last line without a final newline:
$ site-check.sh bad.txt
site-check.sh: bad.txt line 2: invalid check: shop.test:8080/ 200
site-check.sh: bad.txt line 3: invalid check: http://shop.test:8080/ OK
OK 200 1 ms http://shop.test:8080/health
status 3 (0s)
$ site-check.sh -r x sites.txt
site-check.sh: not a whole number: 'x'
status 3 (0s)
$ site-check.sh missing.txt
site-check.sh: cannot read URL file: missing.txt
status 3 (0s)
$ site-check.sh
usage: site-check.sh [-t SECONDS] [-r RETRIES] [-s SLOW_MS] [-d DAYS] URL_FILE
status 3 (0s)
$ site-check.sh empty.txt
site-check.sh: no checks found in empty.txt
status 3 (0s)
A check like this is most useful when it runs from a different machine or network than the website, because a check on the web server itself cannot notice that the server's network connection or DNS records have failed. Scheduled every few minutes with cron (lesson 170) and combined with a notification (lesson 173), it becomes a simple uptime monitor; lesson 198 builds it into a complete project.