I have a long installation script that frequently inserts env variables into .bashrc for immediate and future use, then sources .bashrc to update the env variables. However, this is not working as intended. Unlike when run independently in terminal, running these commands together as a script fails to update the current environment.

Here's a small example:

echo export TEST_BASH=sup >> ~/.bashrc
source ~/.bashrc

The final line will print empty rather than 'sup' as intended. Why is that?

  • 2
    What shell are you executing these commands in? The dash shell (/bin/sh on some Linuxes) does not have source. Also, if any code in ~/.bashrc stops the sourcing of the file to the end (possibly depending on whether it's being sourced by an interactive shell or not), the variable would obviously not be set.
    – Kusalananda
    Commented Nov 14, 2018 at 23:09
  • I'm using #!/bin/bash. Interesting idea that the file might stop. It's just the plain .bashrc file generated by Ubuntu 16.04 with 4 exports for env vars.
    – pir
    Commented Nov 14, 2018 at 23:50
  • at least on debian, the default ~/.bashrc starts with something like case $- in *i*) ;; *) return ;; esac. So, if the shell is not interactive, source ~/.bashrc will return immediately, and any lines you may add at the end have no effect.
    – user313992
    Commented Nov 15, 2018 at 0:35
  • Ah, yes. That's the case here as well.
    – pir
    Commented Nov 15, 2018 at 2:05
  • 1
    I'll have a separate .bash_myenv file and then just source that instead, and add a line to .bashrc to source that one. Thanks! Feel free to provide your comment as an answer.
    – pir
    Commented Nov 15, 2018 at 2:06

1 Answer 1


Your ~/.bashrc file detects whether it's being sourced by an interactive or non-interactive shell:

case $- in
    *i*) ;;
    *) return ;;

When this file is sourced from a script (which is a non-interactive shell), the return branch is taken and the file does not execute to the end.

Adding export statements to the end of the file would mean that these would not be executed when sourced from a script.

The solution may be to write the export statements to a separate file and source that from your script (and possibly from ~/.bashrc as well if you think its needed).

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .