November 15, 2026 路 #60
Works in my shell, fails in cron
The backup works when run by hand. From cron it fails every night with "aws: command not found". Which line is the problem?
# crontab -e
MAILTO=ops@example.com
0 3 * * * /opt/backup/backup.sh
# /opt/backup/backup.sh
#!/usr/bin/env bash
set -euo pipefail
pg_dump "$DATABASE_URL" | gzip > /tmp/db.sql.gz
aws s3 cp /tmp/db.sql.gz s3://acme-backups/Next puzzle in UTC
One try. The first answer sticks.
How to fix it
Cron does not load your login shell. PATH is usually /usr/bin:/bin and exported variables are absent. Set PATH and load the environment in the crontab or script.
Your interactive shell reads profile files that add /usr/local/bin, ~/.local/bin, and exported variables. Cron starts jobs with a tiny environment: a short PATH, HOME, SHELL=/bin/sh, and little else. aws installed to /usr/local/bin is not found, and $DATABASE_URL is unset. With set -u the script stops on the unset variable even before aws.
Fix
PATH=/usr/local/bin:/usr/bin:/bin
MAILTO=ops@example.com
0 3 * * * . /etc/backup.env && /opt/backup/backup.sh >> /var/log/backup.log 2>&1
Or use absolute paths inside the script. A systemd timer with EnvironmentFile= is another clean option, and it logs to the journal.