DEV Community

Cover image for Environment variables not working with CRON?
Łukasz Maśląg for CronMonitor

Posted on

Environment variables not working with CRON?

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
Enter fullscreen mode Exit fullscreen mode

Execute:

* 2 * * * /full/path/backup.sh
Enter fullscreen mode Exit fullscreen mode

Solution 2: Source environment in the Crontab file

# Load the environment
SHELL=/bin/bash
* * * * * source ~/.bashrc && /full/path/backup.sh
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Solution 4: Use .env files (best for production)

* * * * * cd /full/path/ && /usr/bin/env $(cat .env) backup.sh
Enter fullscreen mode Exit fullscreen mode

Best Practices

  1. Always use absolute paths
  2. Set the required environment variables in your cron job or script
  3. Log everything (especially crashes!)
  4. 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)