Unix & Linux
shell environment-variables cron
Updated Fri, 20 May 2022 06:25:43 GMT

How can I run a cron command with existing environmental variables?


How can I run a cron command with existing environmental variables?

If I am at a shell prompt I can type echo $ORACLE_HOME and get a path. This is one of my environmental variables that gets set in my ~/.profile. However, it seems that ~/.profile does not get loaded fron cron scripts and so my scripts fail because the $ORACLE_HOME variable is not set.

In this question the author mentions creating a ~/.cronfile profile which sets up variables for cron, and then he does a workaround to load all his cron commands into scripts he keeps in his ~/Cron directory. A file like ~/.cronfile sounds like a good idea, but the rest of the answer seems a little cumbersome and I was hoping someone could tell me an easier way to get the same result.

I suppose at the start of my scripts I could add something like source ~/.profile but that seems like it could be redundant.

So how can I get make my cron scripts load the variables from my interactive-shell profile?




Solution

In the crontab, before you command, add . $HOME/.profile. For example:

0 5 * * * . $HOME/.profile; /path/to/command/to/run

Cron knows nothing about your shell; it is started by the system, so it has a minimal environment. If you want anything, you need to have that brought in yourself.





Comments (5)

  • +0 – What does the . before the script do? (not sure how I would man that). Why is this different from source? — Dec 21, 2011 at 19:26  
  • +0 – The . command is the original command for source. They are equivalent within the shell and a bit easier to type, especially within a crontab. To get more info, type help . or search for ^SHELL BUILTIN COMMANDS in the man page for bash or at the top of man zshbuiltins. Running type .` will tell you that the command is a builtin. — Dec 21, 2011 at 19:38  
  • +0 – Depending on Linux distributions, you may need to change .profile by .bash_profile. Check which .profile file exists in the user's home directory. — May 17, 2013 at 12:37  
  • +4 – It's likely that if it isn't working, it's because the SHELL for the cron script isn't set to bash, so it's not executing the same way you might expect. — Jul 10, 2015 at 18:32  
  • +1 – Was under the impression that sourcing the .profile and then using ; would cause it to be run in another process that doesn't actually give them over to the command, and that it should be done as $HOME/.profile && /some/command/here — Jul 15, 2019 at 18:44  


Linked Articles

Local articles referenced by this article: