Using same variable in 2 different scripts that run at the same time

Hi,

I have two scripts that use the same variable. Say suppose I export that variable in script 1 and try to use it in script 2 where I have declared it locally, what will be the effective value of the variable? Will it take the exported value or the locally declared?

example:
Script1
ABC=$FILENAME
export ABC

Script2
ABC=XYZ.txt
echo $ABC --> what will be the output here

Given that you overwrite ABC before you print it in script 2, ABC will always end up "xyz.txt" in that script no matter what it was before. Their values aren't protected in any way. But that's beside the point...

Variables don't travel "sideways" like that. They don't actually travel at all -- each and every program has its own, independent set of exported variables, called the 'environment'.

When you run a script or program, it gets a copy of your current environment. But the copy is unconnected. Change the child and the parent remains the same, and vice versa.

If you wanted the same variable to be set in two different programs, either set it earlier in your ~/.profile or ~/.bashrc file so it gets exported on login for you, or have a little config file thing for your scripts to source:

# littleconfigfile
# Some shells don't like export VAR=asdf.  To be safe, break it in half.
VAR=asdf
export VAR
#script1
. littleconfigfile
echo "$VAR"
#script2
. littleconfigfile
echo "$VAR"

The "." operator runs the given script inside the current shell. This is very different from just executing './littleconfigfile' because . allows you to set your own variables instead of setting variables in a useless copy.

Got it! Thanx.

I actually have multiple sctipts that use the same variables in them and they all use export function in each of these scripts. My doubt is that if I would run all these scripts parallely using a single cron, will they confuse with the value of this common variable or it doesnt matter at all?

Thanks

Each process is its own private, independent universe. The value of 'VARIABLE' in some other process' memory doesn't matter to them one bit. All they start with is whatever values cron happens to have the instant it starts them -- which is, intentionally, almost a clean slate. And once they're started nothing from the outside affects them.

Awesome! Thanks for your advice.