I have written various scripts to launch Java server applications, which are typically run for 24 hours before being shut down (by invoking the same script with a different parameter).

The script relies on environment variables defined in a file: ~/<user>.env, which I source from .bashrc.

This works fine when invoking the script from the command line but if I want to add the script as a crontab entry I run into the problem where .bashrc isn't read.

My question: What is the best practice approach for solving this problem? I realise I could define a crontab entry such as:

* * * * 1-5 /usr/bin/bash -c '. /home/myuser/myuser.env && /home/myuser/scripts/myscript.sh'

... but this seems plain ugly. Alternatively I could source myuser.env at the beginning of every script, but this would become a nightmare to maintain.

Any help appreciated.


I usually address this with a short cron wrapper script:

#!/bin/bash
[ -r $HOME/.bashrc ] && . $HOME/.bashrc
[ -r $HOME/.profile ] && . $HOME/.profile
exec "$@"

Then just prefix the command in crontab with your wrapper:

* * * * 1-5 ~/scripts/cron-wrapper ~/scripts/myscript.sh
* * * * 1-5 ~/scripts/cron-wrapper ~/scripts/myotherscript.sh

Some versions of cron allow you to set variables directly in crontab. Unfortunately, I don't get to use those at work.


I actually discovered a fairly elegant solution by adding the '-l' (--login) flag to my bash command, which causes it to source all login files, including .bashrc. Hence my crontab command is simply:

* * * * 1-5 /usr/bin/bash -lc '/mnt/group/core/deploy/scripts/test.sh' > /dev/null 2>&1