I'm running the following command and would expect that it would return me BAR, as the new shell I create will run .mybashrc first, where it sets $FOO before echo $FOO will execute.

bash --rcfile .mybashrc -c 'echo $FOO'


export FOO="BAR"

However the result is empty. What has gone wrong?


By default, non-interactive bash executions do not load initialization files, such as .bashrc or the target of your --rcfile option. As described in the man page:

An interactive shell is one started without non-option arguments and without
the -c option whose standard input and error are both connected to terminals
... or one started with the -i option.

So you can get the behavior you want by forcing bash to act like an interactive shell with -i:

bash --rcfile .mybashrc -ci 'echo $FOO'
| improve this answer | |
  • This works, but apparently not when started from an init script (on a cloud VM). In that case it gives the error "no job control in this shell", maybe because there's no TTY. Is there a way to use an rcfile without the shell being interactive? – z0r May 27 '14 at 23:56
  • 3
    @z0r Non-interactive, non-login bash shells should execute the contents of the file specified in $BASH_ENV. – dg99 May 27 '14 at 23:58
  • Cool, that works. One thing to be aware of when using BASH_ENV: if you start sub-shells like BASH_ENV=./testrc bash -c './test.sh' then the rcfile will execute twice, unless it unsets BASH_ENV. – z0r May 28 '14 at 0:31
  • @z0r You probably have a shebang (#!) at the beginning of test.sh, meaning your command as written is invoking bash twice, and thus testrc gets sourced twice. You should change your command to either BASH_ENV=./testrc bash ./test.sh or BASH_ENV=./testrc ./test.sh. – dg99 May 28 '14 at 16:36
  • You're right, but (outside this test) I don't control the rc file. I'm worried that it might spawn a sub-shell itself, which would result in infinite recursion. My current solution is to have a wrapper rc file that unsets BASH_ENV at the start and then sources the target, which is specified by another environment variable. – z0r May 28 '14 at 23:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.