Build a Website Uptime Checker

Su Suriya Ravichandran Updated 06 Dec 2026
12 min read ·Lesson 198 of 205

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

  1. Read URLs from the command line, from a file (-f), or both. Blank lines and # comments in the file are ignored.
  2. Request each URL with a timeout (-t), following redirects.
  3. Retry a failed check (-r) before declaring the site down, so one lost packet does not raise an alarm.
  4. Classify the result: UP (status 2xx or 3xx and fast enough), SLOW (answered, but slower than -s milliseconds) or DOWN.
  5. Explain every failure in plain words.
  6. Log each check to a CSV file (-l) for later analysis.
  7. 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/null discards the downloaded body.
  • -L follows redirects, so http://example.com that redirects to https://example.com counts as up.
  • --max-time 5 aborts 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 codeMeaning
0A response was received (any status code)
6Could not resolve the host name (DNS problem)
7Connection refused (nothing is listening on that port)
28Operation timed out
35, 60TLS/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, leaving 1 (the whole seconds).
  • ${secs#*.} removes everything up to the first dot, leaving 603941 (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 as 0 or 08 could 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
  • /slow answered correctly but took 1600 ms, above the 1000 ms limit, so it is SLOW. A slow site is often the first sign of trouble.
  • /missing and /error answered, but with an error status. The code column shows what the server said, and the note repeats it.
  • /hang accepted the connection and never answered. Only the timeout saved the script, and the code is 000 because no response arrived.
  • Port 9 has no program listening, so the connection is refused immediately.
  • no-such-host.invalid cannot be resolved, which is a DNS failure. (.invalid is 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 (-o to a temporary file from mktemp) and use grep -q to verify that the page contains an expected word. Some failures return 200 with an error page.
  • Certificate expiry. Use openssl s_client to 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 UP to DOWN or back, to avoid repeated emails during a long outage.
  • Parallel checks. Start each check in the background with & and collect the results with wait (lesson 138) so that a list of 200 sites finishes in seconds.
  • Custom headers and methods. Add -H for authentication tokens or -I to send HEAD requests, which are cheaper for large pages.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Build a Website Uptime Checker and get answers drawn from it.

Signed-in readers only.