0

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
echo $TEST_BASH

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 Nov 14 '18 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 Nov 14 '18 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. – mosvy Nov 15 '18 at 0:35
  • Ah, yes. That's the case here as well. – pir Nov 15 '18 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 Nov 15 '18 at 2:06
2

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

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

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).

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.