Exporting environment variables from sourced scripts

Can someone point me towards some documentation or indeed clarify whether sourcing a bash script should allow me to export environment variables from the source'ed script which then become available in the ‘top level’ environment (and hence inherited in any subsequent processes)? For example, commonEnv.sh below export's MYVAR, however, this variable is not available in runTests.sh in my tests:

    - source ./scripts/commonEnv.sh # assume this exports MYVAR
    - ./scripts/runTests.sh  # MYVAR not available within this script


Here is an example repository that demonstrates what I am trying to achieve:


Here is the behaviour on CircleCI (not working):


And here is the behaviour on Travis (working):


Any thoughts/insights much appreciated.

I need to be able to do this too. It seems as if every command step is given a completely separate instance of bash to run in or something. It’s also quite hard to test by pushing small iterations, trying to make it work on CI when it already works locally…

I just tested and this indeed looks to be true; if I run command1 && command2, command 2 can use env set from command1 but command3 on a new line in the yml cannot. So it does seem as though each separate command is run using an isolated shell or something…I might have to resort to storing my envs vars in temp files instead, so that subsequent commands can access them…

More editing, more follow ups. I found this https://www.compose.io/articles/experience-with-circleci/

Which mentions that David Lowe of Circle says:
“You’ve got the right idea, but unfortunately, ‘export AWSSECRETKEY’ won’t quite work because each command runs in a separate shell”

And then he goes on to recommend storing them in a files, as I suggested, but instead there is actually an env file for Circle, you can add to it from one script by doing:
“echo ‘export AWS_SECRET_KEY=1234’ >> ~/.circlerc”

It’s just annoying to emulate/test this locally…but at least it will (probably) work!

1 Like

I figured out a work around for this topic. A solution is, in your machine tag, you can overwrite your script to echo the export statement and append it to the $HOME/.circlerc, this assures the variable will prevail. Like this:

    - echo export VARIABLE=\"HELLO WORLD\" >> $HOME/.circlerc
    - cat $HOME/.circlerc
     version: 2.7.11

Hope this can help!

1 Like

does the $HOME/.circlerc hack still works on 2.0 builds?

update: I found out that, in 2.0, $BASH_ENV has the name of a temp file that gets sourced in each build. This means echo export VARIABLE='HELLO WORLD' >> "$BASH_ENV" should work there.