Articles / Linux

  • linux
  • cron
  • shell
  • sysadmin
  • debugging
  • environment-variables

Why a Cron Job Runs Fine by Hand and Fails at 3am

You run the backup script, it works. You put the same line in crontab, and at 3am it does nothing, or half of something. The script is not broken. Cron is not running it in your shell, and almost everything your terminal quietly provides is missing.

This is a tour of what is different, and a way to reproduce the failure at a reasonable hour instead of waiting for the night.

What cron actually gives your job

A job started by cron gets a tiny environment. On Debian and Ubuntu (Vixie-style cron) it is roughly this:

  • SHELL=/bin/sh, not bash, and not whatever your login shell is
  • PATH=/usr/bin:/bin, so no /usr/local/bin, no ~/go/bin, no ~/.cargo/bin
  • HOME and LOGNAME set from the passwd entry
  • a working directory of your home directory, not wherever the script lives
  • no terminal, no SSH_AUTH_SOCK, no DISPLAY, no XDG_RUNTIME_DIR

Nothing from .bashrc, .profile or /etc/environment is read, because no login or interactive shell is involved. Details vary a little between cron implementations, so check man 5 crontab on your own machine.

Reproduce it with an empty environment

Instead of guessing, run the command the way cron would. env -i starts with nothing, and you add back only what cron supplies.

cd ~ && env -i \
  HOME="$HOME" LOGNAME="$USER" SHELL=/bin/sh \
  PATH=/usr/bin:/bin \
  /bin/sh -c '/home/andy/bin/backup.sh' </dev/null

The </dev/null matters too: cron gives the job no terminal, so anything that prompts, or checks isatty, behaves differently. If the script now fails, you have your reproduction, and you can fix it in daylight.

The usual culprits, in rough order of frequency

  1. PATH. The script calls restic, node or go, which lives in /usr/local/bin or your home directory. By hand it is found; under cron you get "command not found" with exit status 127.
  2. Relative paths. ./config.yaml resolves against your home directory, not the script's directory.
  3. Bashisms under sh. [[ ... ]], arrays and <(...) fail when SHELL=/bin/sh is dash.
  4. Missing secrets. A variable you export in your profile is simply absent.
  5. No agent. An SSH push that relied on ssh-agent now has no key to offer.
  6. Things that are not ready at 3am. A mount that has not appeared, a network that is down, a token that expired.

The first four are fixed by being explicit. Set PATH at the top of the crontab, or better, use absolute paths for every binary and cd to a known directory inside the script.

#!/bin/sh
set -eu
cd "$(dirname "$0")"
/usr/local/bin/restic backup /srv/data

Quick detour: the percent sign

This one is genuinely odd. In a crontab line, an unescaped % is turned into a newline, and everything after the first one is fed to the command as standard input. So this line breaks in a way that looks like a typo in date:

0 3 * * * tar czf /backup/site-$(date +%F).tgz /srv/site

Cron sees the command end at date + and passes F)... as stdin. The fix is to escape it as \%F, or put the logic in a script where % means what you expect. It is a relic of the original format, and it still bites people decades later.

Where did the error go?

When a cron job fails, it did print something. The problem is where. Cron mails output to the job's owner, and on a machine with no mail transfer agent that output goes nowhere. So the job fails silently and you conclude nothing ran.

First, check that cron started it at all. On Debian-family systems:

journalctl -u cron --since "03:00" --until "03:10"
# or, on systems logging to a file
grep CRON /var/log/syslog

If the line is there, cron did its part and your script is the suspect. Then give the job somewhere to talk:

0 3 * * * /home/andy/bin/backup.sh >>/var/log/backup.log 2>&1

The order matters: >>file 2>&1 sends both streams to the file. Written the other way round, stderr still goes to the old stdout. Make sure the log path is writable by the user the job runs as, or the redirect itself fails before your script starts.

Make failure loud

A script that logs its own errors is better than one that relies on mail. Use set -eu so it stops on the first failure, and consider set -o pipefail if you are on bash. Add a timestamp to the log so you can match runs to the 3am window.

For jobs you really care about, push the success signal outwards: have the script ping a dead-man's-switch URL or touch a file on success, and alert when it goes stale. Absence of an error message is a poor signal, because a job that never ran also prints nothing.

Is a systemd timer better?

Partly. A timer runs a service unit, so you get journald logging by default, a clean and declared environment, and systemctl start backup.service to run the exact job on demand. That last point removes most of the "works by hand" gap, because by-hand and scheduled runs become the same thing.

It does not fix a script that assumes your interactive PATH; the service environment is minimal too. But the failure shows up in journalctl -u backup.service instead of vanishing. For anything beyond a one-liner, that alone is worth the extra two files.