Home > Software engineering >  Sharing variables in different bash scripts
Sharing variables in different bash scripts

Time:10-24

Let's say I have a script script1.sh like

#!/bin/bash
#do something
export THING="a"
source script2.sh & #so running in background
sleep 1 #or do something
export THING="b"
source script2.sh & #so running in background

So exporting a variable THING, read by script2.sh:

#!/bin/bash                                                                                                                                    

echo "PRINT1: ${THING}"
sleep 5
echo "PRINT2: ${THING}"

Is it correct to assume that script2.sh is "freezing" the value of THING at the moment of the call? (i.e. so it's not changing during the executing even if running in background).

I tested this and it seems the case but I want to check that it is the expected general behavior.

Thanks in advance, SL

CodePudding user response:

Is it correct to assume that script2.sh is "freezing" the value of THING at the moment of the call?

Yes. The value is not "frozen", you can change it. It's just a copy.

Every process has its own environment. The child process is created as a copy of the current environment at the moment of the child creation.

  • Related