Debug cron script
Cron jobs often behave differently from the same script run in an interactive shell because cron starts a minimal environment: no login scripts, no familiar PATH, and no loaded dotfiles.
When this appliesβ
Use this runbook when a script works in your terminal but produces different output or fails as a cron job.
Diagnostic stepsβ
1. Reproduce the cron environmentβ
Run the script with a stripped environment to confirm the issue:
env -i /path/to/your/script.sh
Or run it as root if the crontab is owned by root:
sudo env -i /path/to/your/script.sh
A better default is to make the script executable and call it directly:
chmod +x /path/to/your/script.sh
env -i /path/to/your/script.sh
2. Harden the scriptβ
Inside the script itself:
- Use absolute paths for every command and file.
- Export the PATH you need explicitly.
- Do not rely on
~expansion or aliases.
#!/bin/bash
export PATH=/usr/local/bin:/usr/bin:/bin
LOG_FILE=/var/log/my-job.log
/usr/local/bin/my-command >> "$LOG_FILE" 2>&1
3. Trace executionβ
Add a debug trap to see each command as it runs:
#!/bin/bash
set -x
trap "set +x; sleep 5; set -x" DEBUG
The sleep 5 gives you time to read the trace between commands. Remove it once the bug is found.
4. Inspect cron logsβ
Most systems log cron output to /var/log/syslog or /var/log/cron. Check there for the exact error and exit code.
Completion criterionβ
The cron job is fixed when:
- The script runs successfully under
env -i. - The script uses absolute paths and explicit environment variables.
- The cron entry matches the user and path you tested.
- A test run in cron produced the expected output or log entry.