Hi I am curious if it is possible to execute a bash script inside bash rc. It would seem to create a infinite loop unless there was some way to tell it to not try and start a new shell.

Here is an example


echo Hello World


export HELLO_WORLD=$(bash_script.sh)    

A script is executed by a non-interactive shell, while .bashrc is only automatically sourced by interactive shells.

There is a way to trigger an infinite loop, though. Every bash shell, interactive or not, checks if the variable BASH_ENV is set and, if so, uses its value as the name of a file to source. In this case, executing a bash script from this file would result in the infinite loop, so are must be taken. In practice, though, this script would (as its name suggests) simply be used to set environment variables for use by the shell, not execute arbitrary code.

  • So, how can such an infinite loop prevented? – aggsol Jul 11 '16 at 13:07

Ok I figured out how to do this. In .bashrc just do:

export HELLO_WORLD=$(source bash_script.sh)
  • 3
    There's no reason, so far as I can tell, for you to have it assign the result of that script to a variable. You could just as easily have the line source bash_script.sh in your .bashrc – HalosGhost May 11 '14 at 2:38

You do not need to do anything. Simply launching a bash script will not cause your .bashrc to be invoked.

The only time your .bashrc will get invoked is if bash is interactive. When you launch a script, that script is not interactive.

From the bash 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 (as deter‐ mined by isatty(3)), or one started with the -i option. PS1 is set and $- includes i if bash is interactive, allowing a shell script or a startup file to test this state.

The important bit here is "started without non-option arguments". When you launch a script, the first argument to bash is the path to that script. Thus it has a non-option argument and is not interactive.


Put this as line 1:

[ -z "$PS1" ] && return # If not interactive, exit
  • 1
    This isn't a very good test as PS1 could be set even in non-interactive mode. The way to test for interactive mode in bash is by doing [[ "$-" == *i* ]] && echo "I'm interactive" – Patrick May 11 '14 at 2:31

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.