How to use cron with environment variables

· Category: Linux

Short answer

Define variables at the top of your crontab or source a script to set the environment for cron jobs.

Steps

  1. Edit crontab:
crontab -e
  1. Set variables at the top:
SHELL=/bin/bash
PATH=/usr/local/bin:/usr/bin:/bin
[email protected]

0 2 * * * /path/to/backup.sh
  1. Or source a profile in the command:
0 2 * * * . /home/user/.bashrc; /path/to/backup.sh

Tips

  • PATH in cron is minimal; always set it explicitly.
  • Use absolute paths in cron commands.
  • MAILTO sends output via email; redirect to logs in production.

Common issues

  • Commands work in shell but not in cron due to missing PATH or env vars.
  • Locale issues: set LANG explicitly if needed.