You may sometimes need to run a script using cron which has dependencies on environment variables. Because cron runs non-interactively it will require a way to load those environment variables in at run time.


There are multiple ways to achieve this however I like to use the BASH_ENV method. As an example in my case I needed to run a python script which had dependencies on both a custom export path and API key.

First create a custom profile file containing the required environment variables:

touch ~/.python_profile

This file should contain the following:


export PA_API_KEY=<SecretAPIKey>

This profile is then referenced directly in your cron job on the schedule you desire:

# m h  dom mon dow   command
20 6 * * 1-5 BASH_ENV=/home/dave/.python_profile /home/dave/scripts/

In my case, I had a helper bash script to run the required python script to allow bash to load in the required environment variables. Note the helper script should be executable. This will then ensure that those dependencies are solved and will allow your script to run silently in the background to keep you alerted to potential issues in your environment.

Thanks to Nicolas for his even more comprehensive post going over further options.

Loading Environment Variables in a Cron Job
Tagged on:         

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.