Bash and Cron – Why Cron Ignores Variables Defined in .bashrc and .bash_profile

bashcron

I have defined "SHELL" variable in /etc/crontab file:

[martin@martin ~]$ grep SHELL /etc/crontab 
SHELL=/usr/local/bin/bash
[martin@martin ~]$ file /usr/local/bin/bash
/usr/local/bin/bash: ELF 32-bit LSB executable, Intel 80386, version 1 (FreeBSD), dynamically linked (uses shared libs), for FreeBSD 8.0 (800107), stripped
[martin@martin ~]$ 

In addition, all my scripts in /etc/crontab file are started under user "martin". However /home/martin/.bash_profile(for login shell) and /home/martin/.bashrc(for non-logging shell) contain some variables which are ignored in case of cron job, but are used in case I log into machine over SSH or open new bash session. Why cron ignores those variables? Isn't cron simply executing "/usr/local/bin/bash my-script.sh" with permissions for user "martin"?

Best Answer

You can source the file you want at the top of the script or beginning of the job for the user that is executing the job. The "source" command is a built-in. You'd do the same thing if you made edits to those files to load the changes.

* * * * * source /home/user/.bash_profile; <command>

or

#!/bin/bash
source /home/user/.bash_profile

<commands>
Related Question