Environment Variables in Cron - Why They Break Your Scripts
LM
LmaDev
~/blog/environment_variables_not_working_with_cron Crontab / Best Practices

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

# 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

  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
$ share this article
~/newsletter
📬

$ subscribe --cron-tips

Learn best practices for adding cron jobs, practical tips for security, and debugging.

Cron job best practices
Docker integration guides
no spam | unsubscribe anytime
>

# Join 500+ developers monitoring their cron jobs