Ivan Shelonik
Ivan Shelonik

Reputation: 2028

source bashrc doesn't work in cron

All we know that cron ignores variables defined in “.bashrc” and “.bash_profile”, so we have to define it inside cron. I constantly do the same what was written inside the similar question https://unix.stackexchange.com/questions/67940/cron-ignores-variables-defined-in-bashrc-and-bash-profile but still global variables inside .bashrc still not working. I found way to execute it - by defining sh script with "set +a" bashrc script. But "source" still doesn't work.

SHELL=/bin/bash
BASH_ENV=/root/.bashrc
PATH=:/opt/spark/spark-2.2.0-bin-hadoop2.7/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin:/usr/local/sbin
SPARK_HOME=/opt/spark/spark-2.2.0-bin-hadoop2.7
MAILTO=root HOME=/

# m h  dom mon dow   command
* * * * * /bin/bash -c 'source $HOME/.bashrc; echo "SPARK_HOME: '$SPARK_HOME'"; echo "JAVA_HOME: '$JAVA_HOME'"' > /var/log/file.log 2>&1

# DO NOT DELETE LAST LINE

return log file

SPARK_HOME: /opt/spark/spark-2.2.0-bin-hadoop2.7
JAVA_HOME:

also tried to execute this in interactive mode as it was written by mklement0
source .bashrc in a script not working

* * * * * /bin/bash -i source /root/.bashrc; echo $JAVA_HOME > /var/log/file.log 2>&1

As you can see SPARK_HOME is defined inside crontab whilst JAVA_HOME only in .bashrc. P.S in bashrc java home is defined "export JAVA_HOME=/usr/jdk1.8.0_131" All different cron jobs work fine when I change JAVA_HOME to SPARK_HOME, tried different crontab jobs but the answer is the same as it was.

ubuntu kernel version is

uname -a
Linux 6101c32b9243 4.9.62-21.56.amzn1.x86_64 #1 SMP Thu Nov 16 05:37:08 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux

Upvotes: 2

Views: 9415

Answers (1)

tripleee
tripleee

Reputation: 189487

Your last attempt runs bash and sources the file, then exits Bash and runs the echo in the calling shell, which isn't Bash, and of course doesn't know or care that the now-defunct Bash process loaded some settings and then forgot them when it exited. (Or, well, this is what would happen if you fixed the simple quoting errors to keep the source command and its argument as a single string.)

The superficial fix is easy;

* * * * * bash -c 'source $HOME/.bashrc; echo "$JAVA_HOME"' >/var/log/file.log 2>&1

The proper fix, however, is probably to encapsulate all of this in a separate script and keep your crontab really simple.

(Are you really sure your user is allowed to overwrite the log file? Replacing the log once a minute seems rather misdirected, although it's good enough for a quick test to see if the job is running at all.)

Upvotes: 7

Related Questions