7

A non-interactive, non-login shell will try to source any script specified in $BASH_ENV. But how do I guarantee $BASH_ENV is set before a cron job or script has a chance to set $BASH_ENV for any particular session? Is the only option to compile Bash with it hardcoded?

Igorio
  • 7,519
  • 7
  • 20
  • 11

2 Answers2

8

If you want all the bash scripts in your crontab to load BASH_ENV, set it at the crontab level.

BASH_ENV=/path/to/startup.bash
12 34 * * * /path/to/bash_script
1 23 1 * * /path/to/other_bash_script

If you want to set BASH_ENV only for a particular entry, set it there. Then BASH_ENV won't be set for the code listed in the crontab itself, but it's a bad idea to put anything complex there anyway.

12 34 * * * export BASH_ENV=/path/to/startup.bash; /path/to/bash_script
1 23 1 * * /path/to/other_bash_script

If you want a particular script to always load some configuration file, load it directly from within the script.

#!/bin/bash
. /path/to/configuration.bash
…
  • Why do you bother exporting $BASH_ENV if you're only setting it for a single process? Just BASH_ENV=/path/to/startup.bash /path/to/bash_script is the sensible way to do it. – mikeserv Jun 23 '14 at 00:55
4

BASH_ENV is only read in a non-interactive shell, and only if that shell is bash (and not called under the name sh, either). A non-login, interactive shell does not look for $BASH_ENV:

$ export BASH_ENV=/home/cuonglm/bash-env.sh
$ bash -lci '. test.sh'
QWERTY
$ bash -lc '. test.sh'
BASH_ENV read
QWERTY
$ bash -ci '. test.sh'
QWERTY
$ bash -c '. test.sh'
BASH_ENV read
QWERTY

There is no standard file that is run in non-interactive shell for user. You should set it in separated file then source it:

bash -c '. ~/.profile; echo 123'

Or you can set it in some system wide config file like /etc/environment or /etc/bashrc.bashrc.

cuonglm
  • 153,898
  • 1
    I was hopeful /etc/environment would work, but it's not sourced by any shells in Mac OS 10.6 as far as I can tell. /etc/bashrc.bashrc sounds intriguing, but I'm having difficulty tracking down any info on it. Or is that a typo? – Igorio Jun 23 '14 at 18:01