Set Crontab Environment Variables

Crontab runs with a mostly empty environment and a very limited PATH. If your shell scripts run well when executed manually but not running in cronjob, this is mostly the root cause. It is advisable to use complete paths to executables, and export any variables you need in your script when using cron.

There are several approaches you can use to set your environment variables in cron.

Approach 1:

Set each variable you need manually in your script. e.g.
export JAVA_HOME=/usr/local/java-version

Approach 2:

edit your profile:
vi $HOME/.bash_profile (or $HOME/.profile)
run the below for the changes to take effect:
source $HOME/.bash_profile (or $HOME/.profile)

Approach 3:

Save your environment variables to a file (run as the desired user):
env > /path/to/
Then import via your cron script:
env - `cat /path/to/` /bin/sh

Approach 4:
In some cases, you can set global cron variables in /etc/default/cron. There is an element of risk to this however, as these will be set for all cron jobs.

Be the first to comment

Leave a Reply

Your email address will not be published.