Build a Website Uptime Checker
This project builds uptime.sh, a script that checks whether websites are reachable and answering correctly. You give it a list of URLs. For each one it reports UP, SLOW or DOWN, the HTTP status code, the response time and the reason for a failure. It can retry before giving up, write every result to a CSV history file, and exit with a status code that a scheduler or another script can act on.
Lesson 168 showed the basic curl check for one site. This project turns that idea into a small tool: it handles many URLs, tells different kinds of failures apart (DNS, refused connection, timeout, bad status), measures speed, and is safe to run from cron.
What the Script Should Do
- Read URLs from the command line, from a file (
-f), or both. Blank lines and#comments in the file are ignored. - Request each URL with a timeout (
-t), following redirects. - Retry a failed check (
-r) before declaring the site down, so one lost packet does not raise an alarm. - Classify the result:
UP(status 2xx or 3xx and fast enough),SLOW(answered, but slower than-smilliseconds) orDOWN. - Explain every failure in plain words.
- Log each check to a CSV file (
-l) for later analysis. - Exit with status 0 only when every site is healthy.
How curl Measures a Request
Getting Only the Facts
Normally curl prints the page it downloads. For monitoring we do not need the page, only the facts about the request. Three options make that possible:
curl -sS -o /dev/null -L --max-time 5 -w '%{http_code} %{time_total}' http://127.0.0.1:8099/
-s(silent) hides the progress meter, and-S(show errors) brings back error messages even in silent mode. Together they mean: no noise, but never hide a failure.-o /dev/nulldiscards the downloaded body.-Lfollows redirects, sohttp://example.comthat redirects tohttps://example.comcounts as up.--max-time 5aborts the whole request after five seconds. Without a limit, a server that accepts the connection and then says nothing would make the script hang forever.-w(write-out) prints a format string after the transfer.%{http_code}is the final HTTP status and%{time_total}is the total time in seconds.
Expected output:
200 0.001612
The status code and the time are separated by a space, so Bash can split them with parameter expansion.
Why the Exit Code of curl Matters
curl returns two different kinds of information. The HTTP status code says what the server answered (200, 404, 500). The exit code of curl itself says whether a response arrived at all. If the server is unreachable there is no HTTP status, and %{http_code} prints 000. The exit code then tells us why:
| curl exit code | Meaning |
|---|---|
| 0 | A response was received (any status code) |
| 6 | Could not resolve the host name (DNS problem) |
| 7 | Connection refused (nothing is listening on that port) |
| 28 | Operation timed out |
| 35, 60 | TLS/SSL handshake or certificate problem |
A 404 or 500 is a successful transfer with a bad answer, so curl exits with 0. The script therefore has to check both: the exit code for network problems and the status code for application problems.
Design Decisions
Converting Seconds to Milliseconds Without Floating Point
curl reports the time as text such as 1.603941. Bash arithmetic only handles integers, so the script splits the text at the dot and builds the number of milliseconds from the two parts:
secs=1.603941
ms=$(( 10#${secs%.*} * 1000 + 10#${secs#*.} / 1000 ))
echo "$ms"
Expected output:
1603
${secs%.*}removes the shortest match of.*from the end, leaving1(the whole seconds).${secs#*.}removes everything up to the first dot, leaving603941(the microseconds).- The seconds are multiplied by 1000, and the microseconds are divided by 1000 to get the milliseconds.
10#forces base 10. A value such as0or08could otherwise be read as octal, because a leading zero means octal inside$(( )).
The script also sets LC_ALL=C. In some locales a program may print 1,603941 with a comma, which would break this parsing. The C locale always uses a dot.
Retrying Before Declaring a Site Down
A single failed request is weak evidence. A busy network or a server restarting for two seconds can cause it. The check function therefore tries up to retries + 1 times and waits one second between attempts. Only when every attempt fails does the site count as down, and the reason of the last attempt is reported.
for (( attempt = 0; attempt <= retries; attempt++ )); do
# ... run curl ...
(( attempt < retries )) && sleep 1
done
The last line uses && so that the pause happens only between attempts, not after the final one.
Reading a URL List File
A real list of sites is easier to keep in a file than on the command line. The reading loop removes comments and surrounding spaces using only parameter expansion, with no external programs:
line=${line%%#*} # drop everything from the first #
line=${line#"${line%%[![:space:]]*}"} # trim leading spaces
line=${line%"${line##*[![:space:]]}"} # trim trailing spaces
${line%%[![:space:]]*} matches the run of leading white space, and the surrounding ${line#"..."} removes exactly that text. The third line does the same for the end. The loop condition || [[ -n $line ]] makes sure that a last line without a trailing newline is not lost.
Using the Exit Status as the Result
The last line of the script is the arithmetic test (( down + slow == 0 )). A script's exit status is the status of its last command, and an arithmetic test succeeds (status 0) when it is true. So the script exits with 0 when nothing is down or slow and with 1 otherwise, without an explicit exit. This is what makes uptime.sh || notify.sh possible.
The Complete Script
#!/usr/bin/env bash
#
# uptime.sh - check a list of URLs and report which ones are up or down
#
# Usage: uptime.sh [-f FILE] [-t SECONDS] [-r RETRIES] [-s MS] [-l LOGFILE] [URL...]
#
# Options:
# -f FILE read URLs from FILE (one per line, "#" starts a comment)
# -t SECONDS timeout for each request (default: 5)
# -r RETRIES extra attempts after a failure (default: 1)
# -s MS mark a site SLOW when it takes longer than MS milliseconds (default: 1000)
# -l LOGFILE append one CSV line per check to LOGFILE
# -h show this help
#
# Exit status: 0 all sites up, 1 at least one site down or slow, 2 usage error.
set -euo pipefail
export LC_ALL=C # curl prints times with a dot as decimal separator
readonly PROG=${0##*/}
usage() { sed -n '3,15s/^# \{0,1\}//p' "$0"; }
die() {
printf '%s: %s\n' "$PROG" "$1" >&2
exit 2
}
command -v curl >/dev/null || die "curl is required"
timeout_s=5 retries=1 slow_ms=1000 logfile= file=
while getopts ':f:t:r:s:l:h' opt; do
case $opt in
f) file=$OPTARG ;;
t) timeout_s=$OPTARG ;;
r) retries=$OPTARG ;;
s) slow_ms=$OPTARG ;;
l) logfile=$OPTARG ;;
h) usage; exit 0 ;;
:) die "option -$OPTARG needs a value" ;;
*) die "unknown option -$OPTARG (try -h)" ;;
esac
done
shift $((OPTIND - 1))
for n in "$timeout_s" "$retries" "$slow_ms"; do
[[ $n =~ ^[0-9]+$ ]] || die "-t, -r and -s need whole numbers"
done
urls=("$@")
if [[ -n $file ]]; then
[[ -r $file ]] || die "cannot read $file"
while IFS= read -r line || [[ -n $line ]]; do
line=${line%%#*} # drop comments
line=${line#"${line%%[![:space:]]*}"} # trim leading spaces
line=${line%"${line##*[![:space:]]}"} # trim trailing spaces
[[ -n $line ]] && urls+=("$line")
done < "$file"
fi
(( ${#urls[@]} > 0 )) || die "no URLs given (try -h)"
# check URL - set code, ms and reason for one URL (retrying on failure)
check() {
local url=$1 attempt out curl_rc
code=000 ms=0 reason=
for (( attempt = 0; attempt <= retries; attempt++ )); do
curl_rc=0
out=$(curl -sS -o /dev/null -L --max-time "$timeout_s" \
-w '%{http_code} %{time_total}' "$url" 2>&1) || curl_rc=$?
if (( curl_rc == 0 )); then
code=${out%% *}
local secs=${out##* }
ms=$(( 10#${secs%.*} * 1000 + 10#${secs#*.} / 1000 )) # "0.123456" -> 123
if [[ $code =~ ^[23] ]]; then
reason=
return 0
fi
reason="HTTP $code"
else
case $curl_rc in
6) reason="DNS lookup failed" ;;
7) reason="connection refused" ;;
28) reason="timed out after ${timeout_s}s" ;;
35|60) reason="TLS/SSL error" ;;
*) reason="curl error $curl_rc" ;;
esac
fi
(( attempt < retries )) && sleep 1
done
return 1
}
up=0 down=0 slow=0
printf '%-34s %-6s %-5s %8s %s\n' URL STATE CODE TIME NOTE
for url in "${urls[@]}"; do
note=
if check "$url"; then
if (( ms > slow_ms )); then
state=SLOW slow=$((slow + 1))
note="slower than ${slow_ms} ms"
else
state=UP up=$((up + 1))
fi
else
state=DOWN down=$((down + 1))
note=$reason
fi
printf '%-34s %-6s %-5s %6s ms %s\n' "$url" "$state" "$code" "$ms" "$note"
if [[ -n $logfile ]]; then
printf '%s,%s,%s,%s,%s\n' "$(date '+%Y-%m-%dT%H:%M:%S')" "$url" "$state" "$code" "$ms" >> "$logfile"
fi
done
printf '\n%d up, %d slow, %d down (%d checked)\n' "$up" "$slow" "$down" "${#urls[@]}"
(( down + slow == 0 ))
Running the Checker
The examples below use a tiny local test server on port 8099 that answers / with 200, /moved with a redirect, /slow after 1.6 seconds, /missing with 404, /error with 500 and /hang never (within the timeout). Replace these addresses with your own sites.
Checking Healthy Sites
$ ./uptime.sh http://127.0.0.1:8099/ http://127.0.0.1:8099/moved; echo "status $?"
URL STATE CODE TIME NOTE
http://127.0.0.1:8099/ UP 200 0 ms
http://127.0.0.1:8099/moved UP 200 0 ms
2 up, 0 slow, 0 down (2 checked)
status 0
Both sites answer with 200. The /moved page answered with a redirect, and -L followed it to the final page, so the code shown is the final one. Local requests complete in under a millisecond; a real site usually needs 50 to 500 ms.
Checking a List With Every Kind of Failure
The file sites.txt mixes comments, spaces and eight different situations:
# production sites
http://127.0.0.1:8099/
http://127.0.0.1:8099/moved
http://127.0.0.1:8099/slow
http://127.0.0.1:8099/missing # old page
http://127.0.0.1:8099/error
http://127.0.0.1:8099/hang
http://127.0.0.1:9/
http://no-such-host.invalid/
$ ./uptime.sh -f sites.txt -t 3 -r 0 -s 1000 -l log.csv; echo "status $?"
URL STATE CODE TIME NOTE
http://127.0.0.1:8099/ UP 200 2 ms
http://127.0.0.1:8099/moved UP 200 1 ms
http://127.0.0.1:8099/slow SLOW 200 1600 ms slower than 1000 ms
http://127.0.0.1:8099/missing DOWN 404 0 ms HTTP 404
http://127.0.0.1:8099/error DOWN 500 0 ms HTTP 500
http://127.0.0.1:8099/hang DOWN 000 0 ms timed out after 3s
http://127.0.0.1:9/ DOWN 000 0 ms connection refused
http://no-such-host.invalid/ DOWN 000 0 ms DNS lookup failed
2 up, 1 slow, 5 down (8 checked)
status 1
/slowanswered correctly but took 1600 ms, above the 1000 ms limit, so it isSLOW. A slow site is often the first sign of trouble./missingand/erroranswered, but with an error status. The code column shows what the server said, and the note repeats it./hangaccepted the connection and never answered. Only the timeout saved the script, and the code is000because no response arrived.- Port 9 has no program listening, so the connection is refused immediately.
no-such-host.invalidcannot be resolved, which is a DNS failure. (.invalidis a reserved name that never exists, which makes it a safe test.)
The exit status is 1 because at least one site is down or slow.
The CSV History
With -l log.csv, every check appends one line, so the file grows into a history that tools such as awk or a spreadsheet can analyse:
$ cat log.csv
2026-12-02T17:36:50,http://127.0.0.1:8099/,UP,200,2
2026-12-02T17:36:50,http://127.0.0.1:8099/moved,UP,200,1
2026-12-02T17:36:52,http://127.0.0.1:8099/slow,SLOW,200,1600
2026-12-02T17:36:52,http://127.0.0.1:8099/missing,DOWN,404,0
2026-12-02T17:36:52,http://127.0.0.1:8099/error,DOWN,500,0
2026-12-02T17:36:55,http://127.0.0.1:8099/hang,DOWN,000,0
2026-12-02T17:36:55,http://127.0.0.1:9/,DOWN,000,0
2026-12-02T17:36:55,http://no-such-host.invalid/,DOWN,000,0
The columns are time, URL, state, status code and milliseconds. For example, this command counts how often each URL was down. After weeks of data, the sites at the top of the list are the unreliable ones:
awk -F, '$3 == "DOWN" { n[$2]++ } END { for (u in n) print n[u], u }' log.csv | sort -rn
Expected output with the file above (every URL failed once, so all counts are 1):
1 http://no-such-host.invalid/
1 http://127.0.0.1:9/
1 http://127.0.0.1:8099/missing
1 http://127.0.0.1:8099/hang
1 http://127.0.0.1:8099/error
Retries in Action
With -r 2, the script makes three attempts with a one-second pause between them, so a dead site is confirmed after about two seconds:
$ time ./uptime.sh -r 2 -t 2 http://127.0.0.1:9/
URL STATE CODE TIME NOTE
http://127.0.0.1:9/ DOWN 000 0 ms connection refused
0 up, 0 slow, 1 down (1 checked)
real 0m2.021s
Input Errors
$ ./uptime.sh
uptime.sh: no URLs given (try -h)
$ ./uptime.sh -t abc x
uptime.sh: -t, -r and -s need whole numbers
$ ./uptime.sh -f nofile
uptime.sh: cannot read nofile
$ ./uptime.sh -z
uptime.sh: unknown option -z (try -h)
All of these exit with status 2, which separates "the script was used wrongly" from "a site is down" (status 1).
Scheduling and Alerting
The exit status connects the checker to the tools from earlier lessons. This crontab entry (lesson 170) checks the sites listed in /etc/uptime/sites.txt every five minutes, keeps the history, and sends the report only when something is wrong:
*/5 * * * * /usr/local/bin/uptime.sh -f /etc/uptime/sites.txt -l /var/log/uptime.csv > /tmp/uptime.txt || /usr/local/bin/notify.sh "Website problem on $(hostname)" < /tmp/uptime.txt
notify.sh stands for any notification script, such as the one built in lesson 173. Because the report is saved to a file first, the message contains the full table, including the reason for each failure. Combined with a lock file (lesson 171), you can make sure that a slow run is never started twice.
A quick shell test is also useful in deployment scripts (lesson 180). This line waits until a new release answers, and gives up after 30 attempts:
for i in {1..30}; do ./uptime.sh -r 0 http://localhost:8080/health > /dev/null && break; sleep 2; done
Ideas for Extending the Project
- Content check. Download the body (
-oto a temporary file frommktemp) and usegrep -qto verify that the page contains an expected word. Some failures return200with an error page. - Certificate expiry. Use
openssl s_clientto read the certificate date and warn when it expires within 14 days. - Alert only on state changes. Store the last state of each URL in a small file and notify only when it changes from
UPtoDOWNor back, to avoid repeated emails during a long outage. - Parallel checks. Start each check in the background with
&and collect the results withwait(lesson 138) so that a list of 200 sites finishes in seconds. - Custom headers and methods. Add
-Hfor authentication tokens or-Ito sendHEADrequests, which are cheaper for large pages.