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
- Edit crontab:
crontab -e
- Set variables at the top:
SHELL=/bin/bash
PATH=/usr/local/bin:/usr/bin:/bin
[email protected]
0 2 * * * /path/to/backup.sh
- Or source a profile in the command:
0 2 * * * . /home/user/.bashrc; /path/to/backup.sh
Tips
PATHin cron is minimal; always set it explicitly.- Use absolute paths in cron commands.
MAILTOsends 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
LANGexplicitly if needed.