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:
This file should contain the following:
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/some-script-you-want-to-run.sh
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.