I ran my crontab job 0 2 */1 * * /aScript >aLog.log 2>&1
as a 'root' user, and however I found the env is different from env of the 'root' user, and therefore experiencing a different runtime behavior of my scripts.
An attempt fix was placing export commands in rc.d files, but it still didn't show up! I end up placing export commands in the aScript itself.
My question is that is there a better way to approach this problem? and why env is missing even though it is from the same user 'root' ? (I modifies crontab by running 'crontab -e' from the root)
Cron always runs with a mostly empty environment.
HOME
,LOGNAME
, andSHELL
are set; and a very limitedPATH
. It is therefore advisable to use complete paths to executables, and export any variables you need in your script when usingcron
.There are several approaches you can use to set your environment variables in
cron
, but they all amount to setting it in your script.Approach 1:
Set each variable you need manually in your script.
Approach 2:
Source your profile:
. $HOME/.bash_profile
(or. $HOME/.profile
)(You will usually find that the above file will source other files (e.g.
~/.bashrc
-->/etc/bashrc
-->/etc/profile.d/*
) - if not, you can source those as well.)Approach 3:
Save your environment variables to a file (run as the desired user):
Then import via your cron script:
Approach 4:
In some cases, you can set global
cron
variables in/etc/default/cron
. There is an element of risk to this however, as these will be set for allcron
jobs.Cron creates its OWN shell with the use specified through which it will run.
So, if you want to keep the same variable of your user, then try to run it with your own user, instead of root or any other user.
Or
The best way is that export those variables in your own script.
In RedHat CentOS, you could set
/etc/rc.d/init.d/functions
defaultPATH
to permanently set./etc/rc.d/crond
calls functions when starts.I had a similar issue on my AWS. Figured it out like that
gave me
/usr/bin/local/python3
locationand then