Introduction
For example, you've written a script to create a database backup. You execute your script from the terminal in your favorite shell, such as bash, zsh, or another shell. Everything works fine. The database dump is completed as expected.
Then you add the job to cron, e.g., to execute it daily at 2 a.m.
You check the next day, and oops, the backup wasn't completed. Why?
Welcome to the #1 nightmare of cron job debugging: missing environment variables.
Problem
- Cron is running with a minimal environment
- PATH is practically empty
- No user shell variables
- Different working directory
Why this happens
- Comparison of cron and shell environments
- Differences between /bin/sh and /bin/bash
- Security considerations (actually good!)
- Code example showing the difference
Solution 1: Hardcoded paths (bad, but works)
Instead of:
* 2 * * * ./backup.sh
Execute:
* 2 * * * /full/path/backup.sh
Solution 2: Source environment in the Crontab file
# Load the environment
SHELL=/bin/bash
* * * * * source ~/.bashrc && /full/path/backup.sh
Solution 3: Script-level environment (better solution)
#!/bin/bash
export PATH=/usr/local/bin:/usr/bin:/bin
export DATABASE_URL="..."
export DATABASE_USER="..."
export DATABASE_PASSWORD="..."
export DATABASE_PORT="..."
/full/path/backup.sh
Solution 4: Use .env files (best for production)
* * * * * cd /full/path/ && /usr/bin/env $(cat .env) backup.sh
Best Practices
- Always use absolute paths
- Set the required environment variables in your cron job or script
- Log everything (especially crashes!)
- Test in a minimal environment first
Conclusions
Environment variables are the most common cause of "works for me :)" cron errors.
Solution Rating:
- 🥇 Best: .env file + absolute paths + monitoring
- 🥈 Good: Script-level environment configuration
- 🥉 OK: Hardcoded in the script (in simple cases)
- ❌ Avoid: Relying on the user's shell environment
Never miss a failed cron job again
Environmental problems are just one way cron jobs can fail. A bigger problem is when you think the job is running at the scheduled time, but in fact, nothing happens.
For this reason, I wrote a simple cron job monitoring app, CronMonitor, to solve the problem of "Silent CRON Failures":
With the app, you'll get:
✅ Instant alerts when a job fails to run.
✅ Job execution statistics
✅ Free plan forever
For more cron debugging tips, check out: How to debug cron jobs
Top comments (0)