How can I load the users environment variables in a cronjob?
I have a cronjob which should start a script every minute on my Ubuntu machine:
* * * * * /home/user/myscript.sh;
In this script I want to use environment variables like $JAVA_HOME
and $M2_HOME
to automatically start a build process. The problem is that those variables are set in the .bashrc
via export JAVA_HOME=/../..
.
Therefore I source
these files before executing my script:
* * * * * source ~/.bash_profile; source ~/.bashrc; /home/user/myscript.sh;
However, the variables aren't set! To test this I echo
the environment variables via env
to a log file:
env >> ~/env.log
echo $M2_HOME >> ~/env.log
The log file still doesn't contain the variables. Only the following are appended to the file (no $M2_HOME
etc.):
LANGUAGE=en_US:en
HOME=/home/user
LOGNAME=user
PATH=/usr/bin:/bin
LANG=en_US.UTF-8
SHELL=/bin/sh
PWD=/home/user
If I run the script right in my shell all of the variables are print out to env.log
.
The same happens when I put the source
commands into the script file. Only if I remove the export
keyword before the declaration of the variable it is visible by the echo $var
command. But this is not a solution because I don't manage these declarations.
I tried the solution of @tripplee with the limited sh shell problem, but it still doesn't work. I further reduced it to a very simple cronjob without a second script to show the problematic:
* * * * * . $HOME/.bash_profile; . $HOME/.bashrc; env > $HOME/env.log;
cat /home/user/env.log
:
LANGUAGE=en_US:en
HOME=/home/user
LOGNAME=user
PATH=/usr/bin:/bin
LANG=en_US.UTF-8
SHELL=/bin/sh
PWD=/home/user
No comments:
Post a Comment