Introduction

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.

Solution

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:

#!/bin/bash

~/.bashrc
export PYTHONPATH=$PYTHONPATH:$HOME/your/path
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/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.

https://www.baeldung.com/linux/load-env-variables-in-cron-job

Loading Environment Variables in a Cron Job
Tagged on:         

One thought on “Loading Environment Variables in a Cron Job

  • 8th August 2023 at 10:05
    Permalink

    Very interesting. Thank you for writing it, Dave!

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

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