Sub topic 12
Running the check on a schedule
A check you run by hand only helps when you remember to run it. This chapter moves check-disk.sh onto a schedule so it watches block and inode usage while you do other work. It covers cron, systemd timers, the problems scheduled jobs usually hit, and how to confirm the job runs.
This chapter assumes you have:
- Written
check-disk.shas shown in the previous chapter. - Used
sudoand edited files in a terminal editor. - Basic familiarity with
systemdunit names and with reading logs.
What a scheduled check must do
A scheduled job runs without you. It has no terminal, a minimal environment, and nobody watching its output. That changes what "working" means. The job must:
- Run at a predictable interval.
- Stay silent when everything is healthy.
- Leave a record you will actually read when something is wrong.
- Never run on top of a previous run of itself.
The script already satisfies the second point. It prints only when a mount reaches the threshold. The scheduler's job is to supply the other three.
Installing the script
Put the script in a path that every user and scheduler can find, and make it executable:
sudo install -m 755 check-disk.sh /usr/local/bin/check-disk.sh
sudo /usr/local/bin/check-disk.sh 85Run it once by hand first. If it fails here, it will fail silently under a scheduler. Use a low threshold to prove the warning path works:
/usr/local/bin/check-disk.sh 1With a threshold of 1, nearly every mount should produce a warning. If you see none, fix the script before scheduling it.
Scheduling with cron
Cron is the traditional scheduler and is present on almost every server. Edit the root user's crontab so the job can read every filesystem:
sudo crontab -eAdd the line from the spine:
*/15 * * * * /usr/local/bin/check-disk.sh 85 2>&1 | logger -t check-diskThe line has two parts.
*/15 * * * *means "every 15 minutes". The five fields are minute, hour, day of month, month, and day of week.2>&1 | logger -t check-diskmerges standard error into standard output and pipes both tologger. Theloggercommand writes each line to the system log, and-t check-disktags it so you can filter on that tag later.
Because logger consumes the output, cron has nothing left to email. That is intended here. Without the pipe, cron mails any output to the job's owner, which on many servers goes to a mailbox nobody reads or fails because no mail system is installed.
The system-wide alternative
You can also place the job in /etc/cron.d, which keeps it in a file you can manage with configuration tools. Files in this directory have an extra field naming the user:
SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
*/15 * * * * root /usr/local/bin/check-disk.sh 85 2>&1 | logger -t check-diskSave this as /etc/cron.d/check-disk, owned by root with mode 644. On Debian and Ubuntu, cron skips files in this directory whose names contain a dot, so use check-disk and not check-disk.cron.
Why cron jobs fail when the command works by hand
Most failures come from the difference between your login shell and cron's environment.
| Problem | Cause | Fix |
|---|---|---|
| "command not found" | Cron's default `PATH` is short, often `/usr/bin:/bin` | Use absolute paths, or set `PATH` at the top of the crontab |
| Script does not start | File is not executable, or has Windows line endings | `chmod 755`, and check with `file check-disk.sh` |
| Works as you, fails in cron | The job runs as a different user | Install it in root's crontab or name the user in `/etc/cron.d` |
| Bash features fail | Cron runs commands with `/bin/sh` | The script's `#!/usr/bin/env bash` line handles this when the script is run directly |
| No evidence the job ran | Output goes nowhere | Pipe to `logger` and check for cron's own log entries |
The pipeline also has a subtle effect. In cmd | logger, the shell reports the exit status of logger, not of your script. If check-disk.sh crashes, cron still sees success. The -t tag will show only whatever the script printed before it died. If you need to catch script failures, have the script print a clear error line on failure, or use the systemd option below, which tracks the script's exit status directly.
Preventing overlapping runs
A 15-minute interval is long for a script that takes under a second. On a server with a hung network filesystem, though, df can block for a long time. Cron will keep starting new copies, and each one hangs too. Use flock so a new run exits immediately if the previous one is still active:
*/15 * * * * flock -n /run/lock/check-disk.lock /usr/local/bin/check-disk.sh 85 2>&1 | logger -t check-diskThe -n option tells flock not to wait. If the lock is held, it exits at once and the new run does nothing.
A related point: the script excludes tmpfs, devtmpfs, and squashfs with -x. A stuck NFS mount can still make df hang. If you have network mounts you do not need to monitor, add more -x options such as -x nfs4.
Scheduling with a systemd timer
Systemd timers do the same job and add features cron lacks: per-job status, logs captured automatically, and catch-up after downtime. A timer needs two unit files, a service that says what to run and a timer that says when.
Create /etc/systemd/system/check-disk.service:
[Unit]
Description=Check disk space and inode usage
[Service]
Type=oneshot
ExecStart=/usr/local/bin/check-disk.sh 85
SyslogIdentifier=check-diskCreate /etc/systemd/system/check-disk.timer:
[Unit]
Description=Run check-disk every 15 minutes
[Timer]
OnCalendar=*:0/15
Persistent=true
[Install]
WantedBy=timers.targetThen load and start the timer:
sudo systemctl daemon-reload
sudo systemctl enable --now check-disk.timer
systemctl list-timers check-disk.timerSome details worth knowing:
Type=oneshotmeans systemd waits for the script to finish and records its exit status.- Systemd sends the script's output to the journal, and
SyslogIdentifier=check-diskgives it the same tag the cron version used. You do not needlogger. Persistent=truemakes systemd run a missed job after the machine was off at its scheduled time.- Systemd will not start a oneshot service that is still running, so you get overlap protection without
flock. - You enable the timer, not the service.
Choosing between them
| Consideration | cron | systemd timer |
|---|---|---|
| Setup effort | One line | Two files plus a reload |
| Availability | Nearly every Linux | Systems running systemd |
| Overlap protection | Needs `flock` | Built in for oneshot services |
| Failure visibility | Hidden by the `logger` pipe | `systemctl status check-disk.service` shows the exit code |
| Catch-up after downtime | No | Yes, with `Persistent=true` |
On a systemd-based server, the timer is usually the better choice. Use cron when you want the simplest possible setup or must support older systems.
Confirming the job runs
Do not assume it works. Check both that the scheduler fires and that the output lands where you expect.
# Did the scheduler start it? (systemd)
systemctl list-timers check-disk.timer
systemctl status check-disk.service
# Did cron start it? (Debian/Ubuntu journal)
journalctl -u cron --since "1 hour ago" | grep check-disk
# What did the check report?
journalctl -t check-disk --since "1 day ago"On servers that use rsyslog, the tagged lines also appear in /var/log/syslog or /var/log/messages:
grep check-disk /var/log/syslogThe service name for cron is cron on Debian and Ubuntu and crond on RHEL-family systems.
Repeated warnings
A filesystem that stays at 90 percent produces a warning every 15 minutes, which is 96 lines a day. Those lines are a small amount of data, but they train people to ignore the log. You have three reasonable options:
- Accept the repetition and let your log monitoring deduplicate it.
- Lengthen the interval to hourly for slowly growing servers. Change the cron field to
0 * * * *, or the timer toOnCalendar=hourly. - Add two thresholds to the script, such as a warning at 85 and a critical message at 95, so the severe case stands out.
Do not make the interval so long that a fast-growing log can fill a disk between runs. A runaway process can write several gigabytes in minutes. For that case a shorter interval, or a monitoring system that alerts on growth rate, is more useful than a fixed threshold.
Exercise
A teammate's cron entry */15 * * * * check-disk.sh 85 | logger -t check-disk runs fine when typed in a shell but never logs anything from cron. Name two likely causes and a fix for each.
Show answer
First, cron's short PATH does not include /usr/local/bin, so check-disk.sh is not found. Fix it by using the absolute path /usr/local/bin/check-disk.sh, or by setting PATH in the crontab. Second, the entry is in a normal user's crontab, so df still works but the script may lack permission or the user may not have been the intended one; install it in root's crontab or in /etc/cron.d with root named as the user. Also, standard error is not redirected, so error messages such as "command not found" are mailed or lost instead of reaching logger; add 2>&1.
Exercise
You switch the check to a systemd timer. After systemctl enable --now check-disk.service, nothing runs every 15 minutes. What went wrong, and which command shows the next scheduled run once fixed?
Show answer
You enabled the service instead of the timer. A oneshot service enabled on its own runs once at boot or start, not on a schedule. Run sudo systemctl enable --now check-disk.timer, then systemctl list-timers check-disk.timer to see the next and last run times.