By default, cron does not read environment variables from files like ~/.bashrc or ~/.bash_profile. This is because cron runs jobs from a non-interactive, non-login shell. However, there are a few ways to load environment variables into a cron job.
One way is to set the BASH_ENV environment variable in the crontab file. The BASH_ENV variable specifies the path to a script that will be executed before the cron job runs. This script can be used to load environment variables.
For example, the following crontab entry would set the MY_VAR environment variable to “Hello, Cron” before running the command /home/user/backup.sh:
0 10 * * * BASH_ENV=/home/user/set_env.sh /home/user/backup.shThe set_env.sh script could contain the following code:
export MY_VAR="Hello, Cron"Another way to load environment variables into a cron job is to use the export keyword in the crontab entry itself. For example, the following crontab entry would set the MY_VAR environment variable to “Hello, Cron” before running the command /home/user/backup.sh:
0 10 * * * export MY_VAR="Hello, Cron" /home/user/backup.shFinally, you can also use the export keyword in a shell script that is run by cron. For example, the following shell script would set the MY_VAR environment variable to “Hello, Cron” before running the command /home/user/backup.sh:
#!/bin/bash
export MY_VAR="Hello, Cron"
/home/user/backup.sh