6

Say I have a file called variables.sh that sets two variables.

foo=bar
bar=foo

If I source this file I can use these variables in the current shell, but if I want to use it in a second shell script I would have to export them instead, so the file would have to look like this:

export foo=bar
export bar=foo

It is possible to do some kind of source + export or do I have to change variables.sh so that there is export before every variable is set?

1
10

if I want to use it in a second shell script I would have to export them instead, so the file would have to look like this:

You could source the second file, or have it source variables.sh. There are multiple ways to do what you wask, such as doing an eval over the result of processing the file, but the cleanest way would be to use set -a of bash shell:

          -a      Automatically  mark  variables  and  functions which are
                  modified or created for export  to  the  environment  of
                  subsequent commands.

Thus, you can achieve your goal with:

set -a
source variables.sh

As noted by l0b0, you possibly want to set +a afterwards, so you don't continue autoexporting variables on subsequent shell code.

3
  • Nice, thanks! The reason I wouldn't source the file in the second script is because I want it to run over and over, so it would waste a lot of time just sourcing the same variables over and over when you could do it once. Oct 14 '20 at 23:10
  • 2
    You probably want to set +a after sourcing the file, to exporting everything.
    – l0b0
    Oct 15 '20 at 1:20
  • @l0b0: good point, added into the answer
    – Ángel
    Oct 15 '20 at 23:41

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.