Cron Environment Variables
Configure environment variables for reliable cron job execution.
Important: Cron runs with a minimal environment. Missing variables are a common cause of job failures.
Built-in Variables
PATH
Defines where cron looks for executable commands.
# Set at top of crontab
PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
# Your cron jobs
0 1 * * * backup-script.sh
Default: Usually just /usr/bin:/bin - very limited!
SHELL
Specifies which shell to use for executing commands.
# Use bash instead of default sh
SHELL=/bin/bash
# Now you can use bash features
0 2 * * * source ~/.bashrc && my-script.sh
MAILTO
Email address to send cron job output to.
# Send output to specific email
[email protected]
# Or disable email completely
MAILTO=""
HOME
Sets the home directory for cron jobs.
# Set working directory
HOME=/home/username
# Jobs will start in this directory
0 3 * * * ./local-script.sh
Custom Variables
Setting Custom Variables
# Define custom variables at top of crontab
DB_HOST=localhost
DB_NAME=myapp
API_KEY=your-secret-key
LOG_LEVEL=debug
# Use in cron jobs
0 4 * * * /opt/scripts/backup.sh $DB_HOST $DB_NAME
*/5 * * * * API_KEY=$API_KEY /opt/scripts/monitor.sh
Common Patterns
Complete Environment Setup
# Complete crontab with environment
SHELL=/bin/bash
PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
[email protected]
HOME=/home/username
# Application variables
NODE_ENV=production
DATABASE_URL=postgresql://user:pass@localhost/db
# Jobs
0 2 * * * cd /opt/myapp && npm run backup
*/15 * * * * cd /opt/myapp && node monitor.js
Loading from .env File
# Load environment from file
0 3 * * * cd /opt/myapp && source .env && ./backup.sh
# Or use a wrapper script
0 3 * * * /opt/scripts/env-wrapper.sh backup
Debugging Environment
🔍 Debug Environment Variables
Add this temporary job to see what environment cron has:
* * * * * env > /tmp/cron-env.txt && echo "PATH: $PATH" >> /tmp/cron-env.txt