Search code examples
bashunixinteractive-shell

Bash interactive and non-interactive shell behaviour


I have a hard time with interactive and non-interactive shells. I don't understand which is which.

For example, I have read that non interactive shells usually check for the BASH_ENV variable on their startup and execute whatever it points to.

So, what I did is I set the BASH_ENV to point to some script which only echoes OK. Then I typed in bash in terminal and this script echoed OK. But why? Didn't I call yet another INTERACTIVE shell by typing bash in terminal, and not the other way around? Why did it execute the bash_env? I'm on linux mint maya.


Solution

  • The only thing you can be certain of is what's shown in the manpage for bash (see INVOCATION) - that lists in details what startup files are run in each instance.

    However, there's nothing stopping (for example) one of those startup files running other files which would normally not be run.

    By way of example, if .bash_profile had the following line:

    . ~/.profile
    

    it would also run the .profile script.

    In fact the manpage states:

    When bash is started non-interactively, to run a shell script, for example, it looks for the variable BASH_ENV in the environment, expands its value if it appears there, and uses the expanded value as the name of a file to read and execute. Bash behaves as if the following command were executed:

    if [ -n "$BASH_ENV" ]; then . "$BASH_ENV"; fi

    So, if you put that exact line in your startup scripts for an interactive shell like ~/.bash_profile, you'll also source the file pointed to by BASH_ENV.

    Your best bet is to examine the INVOCATION section to find out which of the files will run, and then track through them (with something like set -x at the top of the script) to see what's getting called from where.