Bash – execute bash script inside .bashrc

bashbashrc

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

bash_script.sh:

#!/bin/bash
echo Hello World

.bashrc

export HELLO_WORLD=$(bash_script.sh)    

Best Answer

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.

Related Question