# Uptime checks with a bash script and a systemd timer

> An uptime check is a script on a different machine that requests your URL on a schedule, checks the status and body, and sends a webhook alert only when the state changes.

URL: https://levelrail.com/learn/monitoring/uptime-checks-with-a-script-and-timer/
Updated: 2026-11-27

An uptime check is a small script on a different machine that requests your URL on a schedule, tests the status code and the response body, and sends a webhook message when the state changes. Run it from a second server so it still works when the monitored one is down, and keep a state file so one outage produces one alert instead of one per minute.

## How it works

The script uses `curl -fsS --max-time 10`. The `-f` flag makes curl exit non-zero on HTTP errors such as 500, `-sS` hides the progress meter but still prints errors, and `--max-time` stops a hung server from blocking the script. The script also looks for an expected string in the body, because a page can return 200 and still be an error screen. It compares the result to the last result stored in a file and calls a webhook only when they differ.

A scheduler runs the script every minute. Both [cron and systemd timers](https://levelrail.com/learn/linux/cron-vs-systemd-timers/)) work. The check must live on another host. If it runs on the monitored server, a power loss or network cut silences it exactly when you need it. See [what to monitor first](https://levelrail.com/learn/monitoring/what-to-monitor-first/)) for why.

## Step 1: Write the script

Save this as `/usr/local/bin/check-site.sh` on the second machine:

```bash
#!/usr/bin/env bash
set -u

URL="https://example.com/"
EXPECT="Welcome"
HOOK="https://example.com/hook"
TOKEN="change-me"
STATE_FILE="/var/lib/check-site/state"

mkdir -p "$(dirname "$STATE_FILE")"
prev="$(cat "$STATE_FILE" 2>/dev/null || echo up)"

body="$(curl -fsS --max-time 10 "$URL" 2>/dev/null)"
rc=$?

if [ "$rc" -eq 0 ] && printf '%s' "$body" | grep -q "$EXPECT"; then
  now=up
else
  now=down
fi

if [ "$now" != "$prev" ]; then
  curl -fsS --max-time 10 -X POST "$HOOK" \
    -H "Authorization: Bearer $TOKEN" \
    -d "{\"text\":\"$URL is $now\"}" >/dev/null 2>&1
  echo "$now" > "$STATE_FILE"
  echo "alert sent: $URL is $now"
else
  echo "ok $URL (state unchanged: $now)"
fi
```

Replace `https://example.com/hook` and `change-me` with your real webhook and token, and never commit the real values to a repository. Make the script executable:

```bash
sudo chmod 755 /usr/local/bin/check-site.sh
sudo mkdir -p /var/lib/check-site
```

The state file is written only after the webhook call, but the script writes it either way here to keep the logic short. If you prefer to retry a failed alert next run, write the file only when the webhook call succeeds.

## Step 2: Run it by hand

Run the script as the user that will own the schedule:

```bash
sudo /usr/local/bin/check-site.sh
```

A healthy site prints `ok https://example.com/ (state unchanged: up)`. To test the alert path, temporarily set `EXPECT` to a string that is not on the page. You should get one down message in your channel, and one recovery message after you restore the value.

## Step 3: Schedule it with cron

The shortest option is one line in `sudo crontab -e`:

```text
* * * * * /usr/local/bin/check-site.sh >> /var/log/check-site.log 2>&1
```

This runs every minute and appends output to a log. Rotate that log (see [log basics with journald and logrotate](https://levelrail.com/learn/monitoring/log-basics-journald-and-logrotate/))) or it will grow slowly forever. The cron basics are in [schedule tasks with cron](https://levelrail.com/learn/server-basics/schedule-tasks-with-cron/)).

## Step 4: Or schedule it with a systemd timer

A timer gives you journal logs and a visible failed state. Create `/etc/systemd/system/check-site.service`:

```ini
[Unit]
Description=Check site uptime

[Service]
Type=oneshot
ExecStart=/usr/local/bin/check-site.sh
```

Then `/etc/systemd/system/check-site.timer`:

```ini
[Unit]
Description=Run the site check every minute

[Timer]
OnBootSec=1min
OnUnitActiveSec=1min
AccuracySec=5s

[Install]
WantedBy=timers.target
```

`OnUnitActiveSec=1min` runs the service one minute after its last activation. If you prefer wall clock times, use `OnCalendar=*:0/1` instead (every minute). Enable it:

```bash
sudo systemctl daemon-reload
sudo systemctl enable --now check-site.timer
systemctl list-timers check-site.timer
```

Read results with `journalctl -u check-site.service --since "10 minutes ago"`. More on units is in [run a service with systemd](https://levelrail.com/learn/server-basics/run-a-service-with-systemd/)).

## Check it worked

- `systemctl list-timers check-site.timer` shows a next run within a minute.
- `journalctl -u check-site.service -n 5` shows `ok ... state unchanged: up` lines.
- Changing `EXPECT` to a missing word sends exactly one down message, not one per minute.
- Restoring it sends exactly one recovery message.
- Stop the monitored service for two minutes and confirm the alert arrives on your phone.

## Edge cases and gotchas

- **Alert spam.** Without a state file you get a message every run during an outage. Always compare to the previous state.
- **One failure is not an outage.** A single dropped packet can flip the state. Require two failures in a row, for example by storing a counter, before you alert.
- **The checker can fail too.** If the second machine dies, nothing alerts. Use a second provider or a hosted checker as a backup, and watch the checker's own heartbeat if you can.
- **Body checks break on redesigns.** A changed headline fails your `EXPECT` string. Pick a stable marker, such as a `/health` route or a footer string.
- **Secrets in the script.** The token sits in a file on disk. Set permissions so only the owner can read it, and do not paste it into logs.
- **Clock and timezone.** Timers use the host clock. A wrong time zone does not break `OnUnitActiveSec`, but it confuses log reading.

## Troubleshooting

| Symptom | Likely cause | Fix |
| --- | --- | --- |
| `curl: (28) Operation timed out after 10001 milliseconds` | Server slow or unreachable | Check the server, firewall and DNS from the checker |
| `curl: (22) The requested URL returned error: 502` | Backend behind the proxy is down | Check the app and proxy logs, see [fix 502 bad gateway](https://levelrail.com/learn/deploy-operate/fix-502-bad-gateway/)) |
| `curl: (60) SSL certificate problem: certificate has expired` | Expired certificate | Renew it and check the renewal logs |
| `curl: (6) Could not resolve host` | DNS problem on the checker or the domain | Test with `dig` from the checker |
| Script runs but no alert arrives | Wrong webhook URL or token | Run the webhook `curl` by hand and read the response |
| `Permission denied` writing the state file | State directory owned by another user | Create it and set ownership to the user running the script |
| Timer shows `n/a` for NEXT | Timer not enabled or unit file has an error | Run `systemctl status check-site.timer` and `systemd-analyze verify` |
| Alert on every run | State file not written | Fix the path and permissions, then rerun |

## Quick reference

```bash
curl -fsS --max-time 10 -o /dev/null https://example.com/
echo $?
sudo systemctl enable --now check-site.timer
systemctl list-timers check-site.timer
journalctl -u check-site.service --since "10 minutes ago"
```

## Related lessons

- [What to monitor first](https://levelrail.com/learn/monitoring/what-to-monitor-first/)): where an outside check fits among the others.
- [Cron vs systemd timers](https://levelrail.com/learn/linux/cron-vs-systemd-timers/)): how to choose a scheduler.
- [Monitor uptime simply](https://levelrail.com/learn/deploy-operate/monitor-uptime-simply/)): the no-script option with a hosted checker.
- [Build a public status page](https://levelrail.com/learn/monitoring/build-a-public-status-page/)): publish the results of this check.
- [Alerting without alert fatigue](https://levelrail.com/learn/monitoring/alerting-without-alert-fatigue/)): keep notifications useful.

Related post: [health checks that pass on a dead container](https://levelrail.com/blog/health-check-passes-dead-container/)).

## Next

Learn where the logs go in [log basics with journald and logrotate](https://levelrail.com/learn/monitoring/log-basics-journald-and-logrotate/)).

## Frequently asked questions

### How do I check if a website is up with curl?

Run curl -fsS --max-time 10 -o /dev/null https://example.com/. With -f it exits non-zero on HTTP errors, -sS keeps it quiet but shows errors, and --max-time stops it hanging.

### Why run the uptime check from a different server?

If the monitored server loses power or network, a check running on it cannot report anything. A second machine also tests DNS, TLS and the network path like a real visitor.

### Cron or a systemd timer for monitoring checks?

Either works. Cron is one line and familiar. A systemd timer gives you logs in journalctl, a clear failure state and options like OnUnitActiveSec to run a set time after the last run finished.

### How do I stop a monitoring script from sending the same alert every minute?

Store the last known state in a file and send an alert only when the state changes from up to down or back. This turns a stream of failures into one alert and one recovery message.


## Sources

- [curl man page](https://curl.se/docs/manpage.html)
- [systemd.timer man page](https://man7.org/linux/man-pages/man5/systemd.timer.5.html)
