Cron Environment Variables Missing
Your cron job can't find DATABASE_URL, API_KEY, or other environment variables? Here's how to fix it.
Why This Happens
When you log into a terminal, your shell loads .bashrc, .bash_profile, or .profile. These files set environment variables like:
export DATABASE_URL="postgres://localhost/mydb"
export API_KEY="sk-xxxxx"
export NODE_ENV="production"
Cron doesn't load these files. It runs with a minimal environment containing only a few variables like HOME, LOGNAME, and SHELL.
Solution 1: Set Variables in Crontab
Declare variables at the top of your crontab:
# Edit crontab
crontab -e
# Add variables at the top
DATABASE_URL=postgres://localhost/mydb
API_KEY=sk-xxxxx
NODE_ENV=production
# Your jobs below
0 * * * * /home/user/scripts/backup.sh
Limitations:
- Values can't contain spaces (use quotes in the command if needed)
- Variables are visible in
crontab -l(security concern)
Solution 2: Source an Env File in Your Script
Create an environment file and source it:
# /home/user/.env
export DATABASE_URL="postgres://localhost/mydb"
export API_KEY="sk-xxxxx"
export NODE_ENV="production"
#!/bin/bash
# backup.sh
# Load environment variables
source /home/user/.env
# Now your script has access to them
pg_dump $DATABASE_URL > backup.sql
Best practice: Set restrictive permissions on your env file:
chmod 600 /home/user/.env
Solution 3: Source .bashrc or .profile
Load your shell's configuration file:
#!/bin/bash
source ~/.bashrc
# Your commands here
Or in the crontab itself:
0 * * * * bash -c 'source ~/.bashrc && /path/to/script.sh'
This works if your env vars are defined in .bashrc, but it also loads everything else which can be slow.
Solution 4: Use a Wrapper Script
Create a wrapper that sets up the environment:
#!/bin/bash
# run-with-env.sh
# Load environment
source /home/user/.env
# Run the actual command
exec "$@"
Then in crontab:
0 * * * * /home/user/run-with-env.sh /home/user/scripts/backup.sh
Solution 5: Inline in Crontab
For simple cases, set the variable inline:
0 * * * * DATABASE_URL="postgres://localhost/mydb" /home/user/scripts/backup.sh
Debugging: Check What Cron Sees
Add a job that dumps the environment:
* * * * * env > /tmp/cron-env.txt 2>&1
Check /tmp/cron-env.txt to see exactly what variables cron has access to.
Security Note
Avoid putting sensitive credentials directly in crontab entries. They're visible to anyone who can run crontab -l as your user. Use an env file with restricted permissions instead.
Never debug silent cron failures again
CronSignal alerts you the moment a job doesn't run. Know about failures before they become disasters.
Start Monitoring Free3 checks free. No credit card required.